为什么具有可选属性的接口(interface)与不具有可选属性的接口(interface)的处理方式不同?如果没有明确定义可选的属性,是否所有属性都被认为是类型断言的可选属性?
interface WithOptionalProperty {
requiredProperty: string;
optionalProperty?: string;
}
//compilation error 'requiredProperty' is missing
let a = { optionalProperty: '' } as WithOptionalProperty;
interface WithoutOptionalProperties {
requiredProperty: string;
anotherRequiredProperty: string;
}
//but this works as expected
let b = { anotherRequiredProperty: '' } as WithoutOptionalProperties;
最佳答案
这是因为如果 A 可分配给 B 或 B 可分配给 A(简化说明),则类型 A 和 B 之间的类型断言会成功。
在您的情况 1 中,这些条件都不成立。但在情况 B 中,其中一个条件成立(因此断言编译正常)。
更多
https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html
双重断言:https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html#double-assertion
关于Typescript 类型断言 - 与可选成员的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38692188/