Search code examples
typescript

Why doesn't typescript undefined type behave same as optional?


Imagine we have interface

interface Foo {
  bar: number | undefined;
}

If we try to create object of type Foo like

const foo: Foo = {};

It won't compile because property bar is missing. But we say that it can be undefined, which will work if we explicitly set it to undefined, but that's exactly same if we do not set it at all. Shouldn't it do exactly same as following?

interface Foo {
   bar?: number;
}

For me this is an issue, because if we consider more complex example, where we have interface with a field, which can be optional by generic type. So like, if generic type is not specified, then field should be undefined, if it is specified, then it should be only of that type. For example

interface Foo<T = undefined> {
    bar: T;
    title: string;
}

const foo1: Foo = {
    title: 'TITLE'
};

const foo2: Foo<number> = {
    title: 'title',
    bar: 12
};

foo1 will fail to compile because property is missing, but it anyway has to be undefined, and if we specify it explicitly it will work, but that's exactly same. I ended up solving this problem with inheritance, where base class doesn't have any generic parameters and the child has it strictly specified. But I am just curious if anyone knows a specific reason why undefined type is handled this way. Because I couldn't find any information about it myself.


Solution

  • The two type signatures aren't entirely equivalent (although they're close enough that the difference may not be apparent at first glance)!

    • bar?: number expresses that the object might not have a field called bar.
    • bar: number | undefined expresses that the object will always have a field called bar, but the value of that field might be set to undefined.

    This difference might matter in some cases, as some runtime behaviors are dependent on the difference between a field being present and a field being set to undefined - consider if you called Object.keys on the object:

    Object.keys({ bar: undefined }) // returns ["bar"]
    Object.keys({})                 // returns []