我的问题与这个问题有关:
我已经回答了这个问题,本质上我的思维模式是:
TypeScript有一对一的变量到类型的映射,并且无法跟踪‘第1行的变量A的类型是.,而第5行的变量A的类型是.’。
当然,这并不是严格意义上的,类型警卫TypeScript就是这样做的。
function usesSomeType(value: string | number) {
value; //(parameter) value: string | number
if (typeof value === 'string') {
value; //(parameter) value: string
// TypeScript knows that the type of value is different on lines 4 and on lines 9.
}
}我的问题是,类型保护是TypeScript有这种行为的唯一情况,还是存在其他情况?
发布于 2022-04-02 03:03:01
这是我所知道的另一种方式
enum objTypes {
TYPE1 = 1,
TYPE2 = 2
}
class Object1 {
objType: objTypes.TYPE1 = objTypes.TYPE1;
x?: number;
}
class Object2 {
objType: objTypes.TYPE2 = objTypes.TYPE2;
y?: number;
}
function useSomeFoo(bar: Object1 | Object2) {
if (bar.objType === objTypes.TYPE1) {
bar.x // accessible, no error.
// bar.y // error
}
}https://stackoverflow.com/questions/71714483
复制相似问题