Alexandra Pickle
Alexandra Pickle

Reputation: 39

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?

Upvotes: 1

Views: 2281

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370589

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)

Upvotes: 4

Related Questions