打字稿:问号与未定义的类型联合
typescript: question mark vs type union with undefined
在指定名称末尾带有问号的成员时,类型签名会自动扩展为包含 undefined
。创建没有这个成员的实例也可以:
interface Option{
val? : number; // hover over val and it tells you that the type is number|undefined
}
let o: Option = {};
val 的推断类型是 number|undefined
。到目前为止,我认为这是问号的唯一效果。但是手动注释类型联合并没有同样的效果:
interface Union{
val : number|undefined;
}
let u: Union = {}; // compiler complains about missing member val
为什么第二个代码示例不正确?
您的第一个选项是 "val is an optional property with type number"。它可以在那里,但不是必须的。
你的第二个选项是 "val is REQUIRED property, which can have a value of either number or undefined"。因此,它会抛出编译器错误。
在指定名称末尾带有问号的成员时,类型签名会自动扩展为包含 undefined
。创建没有这个成员的实例也可以:
interface Option{
val? : number; // hover over val and it tells you that the type is number|undefined
}
let o: Option = {};
val 的推断类型是 number|undefined
。到目前为止,我认为这是问号的唯一效果。但是手动注释类型联合并没有同样的效果:
interface Union{
val : number|undefined;
}
let u: Union = {}; // compiler complains about missing member val
为什么第二个代码示例不正确?
您的第一个选项是 "val is an optional property with type number"。它可以在那里,但不是必须的。
你的第二个选项是 "val is REQUIRED property, which can have a value of either number or undefined"。因此,它会抛出编译器错误。