有一个联合类型的 Typescript 变量A
type A = {
b: true
x: number
} | {
b: false
x: string
}
declare const v: A
我可以正确地将属性分配x
给正确的类型,方法是使用 if 判别块检查属性b
值类型以保护type A
一致性
if (v.b) { // v.x is number
// ok for compiler
v.x = 3
// compiler error as v.x should be number
v.x = ''
} else { // v.x is string
// compiler error as v.x should be string
v.x = 3
// ok for compiler
v.x = ''
}
然而,外部判别块v.x
似乎正确number | string
,编译器不会抱怨分配给x
,number | string
尽管这会破坏type A
一致性
v.x = 3 // ok for compiler
v.x = '' // ok for compiler
有没有办法强制编译器拒绝这个?
在 typescriptlang.org/play 上查看