[英]How to check if property exists if obj is one of types
Let's say I have few interfaces A, B, C implementing common Base.假设我有几个接口 A、B、C 实现了公共 Base。
interface Base {
x: number;
y: number;
z: number;
}
interface A extends Base {
a: true;
}
interface B extends Base {
b: true;
}
interface C extends Base {
C: true;
}
And function with if statements:并使用 if 语句运行:
function foo(arg: A|B|C){
if(arg.a!==undefined){//throws type error
//do stuff for type a
} else if(arg.b !== undefined){//throws type error
//do stuff for type b
} else if(arg.c !== undefined){ //throws type error
//do stuff for type c
}
}
How to correctly check if property exists?如何正确检查属性是否存在? I don't wan't to use any type.
我不想使用任何类型。 Is
//@ts-ignore
only option? //@ts-ignore
唯一的选项吗?
Typescript will only allow access to common properties. Typescript 将只允许访问公共属性。 Since the properties you test are not common to all members of the union, typescript will not let you access them.
由于您测试的属性对于联合的所有成员并不通用,因此 typescript 不会让您访问它们。
You can use an in
type guard instead to test for the presence of the property.您可以改用
in
类型保护来测试该属性是否存在。
interface Base {
x: number;
y: number;
z: number;
}
interface A extends Base {
a: true;
}
interface B extends Base {
b: true;
}
interface C extends Base {
C: true;
}
function foo(arg: A|B|C){
if('a' in arg){
arg.a
} else if('b' in arg){
arg.b
} else {
arg.C
}
}
You can use a type guard :您可以使用类型保护:
function isA(arg: A | B | C): arg is A {
return (<A>arg).a !== undefined;
}
function isB(arg: A | B | C): arg is B {
return (<B>arg).b !== undefined;
}
function foo(arg: A | B | C) {
if (isA(arg)) {
// do stuff for type a
} else if (isB(arg)) {
// do stuff for type b
} else {
// do stuff for type c
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.