简体   繁体   中英

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.

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 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 []

The simple reason appears to be that nobody has implemented it yet. The way the current type checker is implemented it ended up requiring properties of type undefined to be required, but there is a proposal to change the behavior in a way that makes more sense, but nobody has gotten to it yet.

A workaround that keeps the same name for the type and makes the field optional could be achieved using conditional types:

type Foo<T = undefined> = {
    title: string;
} & (T extends undefined ? {} : { bar: T});

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

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

A solution that worked for was to use this utility type:

type KeysOfType<T, SelectedType> = {
  [key in keyof T]: SelectedType extends T[key] ? key : never;
}[keyof T];

type Optional<T> = Partial<Pick<T, KeysOfType<T, undefined>>>;

type Required<T> = Omit<T, KeysOfType<T, undefined>>;

export type OptionalUndefined<T> = Optional<T> & Required<T>;

Example

type MyType = {
    foo: string | undefined;
}

const willFail: MyType = {};

const willNotFail: OptionalUndefined<MyType> = {};

Taken from https://github.com/Microsoft/TypeScript/issues/12400#issuecomment-758523767

Typescript 4.6

type TNullProperties<T> = {
  [K in keyof T as null extends T[K] ? K : never]?: T[K];
};

type TNotNullProperties<T> = {
  [K in keyof T as null extends T[K] ? never : K]: T[K];
};

Theses two can be used together to make only the null properties of an object optional.

{ key1: string | null; key2: string }

becomes

{ key1?: string | null | undefined; key2: string }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM