“typescript“ “type predicate“ 陷阱记录
“typescript” “type predicate” 陷阱记录
起因
一个让我开始怀疑人生的bug.
经过
搞了半天, bar
里面的运行过程还是没有搞懂.
可以去 typescript playground看看.
type A={}function isA(x:any): x is A{return Object.values(x).length==0;
}
type B={_:null
}function foo(x:A|B) {if(isA(x)){x;
// ^?}else{x;
// ^?}
}function bar(x:A|B) {if(isA(x as number)){x;
// ^?}else{x;
// ^?}
}
结果
直接说结论,因为B
的属性的集合是A
的超集,所以,isA
并不能区分A
和B
,对typescript
来说,B
也是A
类型的,所以在foo
的else
里面x
的类型直接变成了never
(: <)