简体   繁体   中英

Can an optional property value be null?

I thought optional properties in TypeScript covered both undefined and null cases. Am I wrong?

If I have the following interface

export interface student {
   id: string;
   major?: string;
}

and API returns

{
   id: '1234',
   major: null
}

will this cause an error?

That will be incorrect, type-wise.

An optional property means that the property may either be of the type on the right (here, string ), or it may be undefined .

interface student {
   id: string;
   major?: string;
}

is very similar to

interface student {
   id: string;
   major: string | undefined;
}

null is not included.

https://www.typescriptlang.org/play?#code/C4TwDgpgBAzsCuATCA7YUC8UDeAoKBAlogFyzABOhKA5gNz4EC2AhgFYD2FA-GXFbQYBfXLgDGHFHFh8EyNJhyMoxMgHIAjACYAzABY1AGmWtOFMingAbK7iFA

(They're not exactly the same though, thanks Patrick Roberts - a type with optional property can be applied to an object which lacks the property entirely, but a required property with | undefined can only be applied to an object which has that property, and the value of the property may be undefined )

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