Reputation: 39
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
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.
(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