typescript 问题: type A { name: string } type B { label: string } type Mixed = A | B const test: Mixed[] = [{label: ‘b’}] 会报错,如何正确定义Mixed的类型?
时间: 2023-02-21 20:12:01 浏览: 176
定义Mixed的类型正确的方法是使用类型断言,告诉编译器这个对象是Mixed类型,并指定它的具体类型。例如:
```
const test: Mixed[] = [{label: 'b'} as Mixed];
```
也可以使用类型判断,检查对象的类型并进行强制转换:
```
const test: Mixed[] = [{label: 'b'}];
test.forEach((item) => {
if ('name' in item) {
const a = item as A;
console.log(a.name);
} else {
const b = item as B;
console.log(b.label);
}
});
```
阅读全文