我有一个联合类型项目,如下所示:
export interface A {
a: number
}
export interface B {
b: string
}
export type MyUnionType = A | B;
Run Code Online (Sandbox Code Playgroud)
我想根据属性 a 或 b 的存在来检查模板中 MyUnionType 类型的对象是否属于 A 类型或 B 类型。
我期望这样的事情应该有效:
<div *ngIf="'a' in item">
{{item.a}}
</div>
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?谢谢!
小智 0
上面的方法是行不通的。当您定义组合类型(例如结合两种或多种类型的 MyUnionType)时,生成的类型需要子类型中存在的所有属性,并且它们都应该存在一个公共属性。
export interface A {
a: number;
c: string;
}
export interface B {
b: string;
c: string;
}
export type MyUnionType = A | B;
Run Code Online (Sandbox Code Playgroud)
下面的代码片段将起作用
<div>
{{item.c}}
</div>
Run Code Online (Sandbox Code Playgroud)
// But below snippet will not work. Since TypeScript does not know which of the three
// potential types a could be.
// Trying to access a property which isn't shared
// across all types will raise an error
<div>
{{item.a}}
</div>
Run Code Online (Sandbox Code Playgroud)
如何使用此类类型在这里有很好的记录: https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html