首页 > 解决方案 > Typescript - 来自各种接口列表的数组项

问题描述

interface NamedAnimal {
  name: string;
}

interface Fish extends NamedAnimal {
  type: 'fish';
  water: 'fresh' | 'salt';
}

interface Dog extends NamedAnimal {
  type: 'dog';
  breed: 'terrier' | 'mutt';
}

type Animal = Fish | Dog;

const animals: Animal[] = [
  { type: 'dog', name: 'rover', breed:'terrier' }
];


function doSomething(animal: Animal) {
  if (animal.breed) {
    // do something doglike.....
  }
}

doSomething(animals[0]);

在上面的例子中,为什么引用“animal.breed”会给我一个错误,说“鱼类型上不存在属性“品种”

如何更改它以使其成为列出的任何类型?

(这不是我的实际代码,而是我遇到的问题的一个例子)。

标签: typescripttypescript-typings

解决方案


类型断言会帮助你。您可以指定在特定情况下要使用的类型。

function doSomething( animal: Animal ) {
   if((animal as Dog).breed) {
      // do something doglike.....
   }
}

推荐阅读