[英]Can an optional property value be null?
I thought optional properties in TypeScript covered both undefined and null cases.我认为 TypeScript 中的可选属性涵盖了 undefined 和 null 情况。 Am I wrong?
我错了吗?
If I have the following interface如果我有以下界面
export interface student {
id: string;
major?: string;
}
and API returns和 API 返回
{
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
.可选属性意味着该属性可能是右侧的类型(此处为
string
),也可能是undefined
。
interface student {
id: string;
major?: string;
}
is very similar to非常相似
interface student {
id: string;
major: string | undefined;
}
null
is not included. null
不包括在内。
https://www.typescriptlang.org/play?#code/C4TwDgpgBAzsCuATCA7YUC8UDeAoKBAlogFyzABOhKA5gNz4EC2AhgFYD2FA-GXFbQYBfXLgDGHFHFh8EyNJhyMoxMgHIAjACYAzABY1AGmWtOFMingAbK7iFA https://www.typescriptlang.org/play?#code/C4TwDgpgBAzsCuATCA7YUC8UDeAoKBAlogFyzABOhKA5gNz4EC2AhgFYD2FA-GXFbQYBfXLgDGHFHFh8EyNJhyMoxMgHIAjACYAzABY1FAGMWK
(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
) (尽管它们并不完全相同,感谢 Patrick Roberts - 具有可选属性的类型可以应用于完全缺少该属性的 object,但是带有
| undefined
的必需属性只能应用于具有该属性的 object,并且属性的值可能是undefined
的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.