Typescript: What's the difference between an optional field and a union with undefined?

Solution 1:

Even at runtime there is a difference between a key with an undefined value and a key that doesn't exist. That TypeScript allows differentiating is not surprising.

Try this:

Object.keys({a: undefined});

If leaving a out and setting it's value to be undefined were the same thing then we'd expect the above to return an empty array, but in fact it returns

[ 'a' ]