typescript - 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”会给我一个错误,说“鱼类型上不存在属性“品种”
如何更改它以使其成为列出的任何类型?
(这不是我的实际代码,而是我遇到的问题的一个例子)。
解决方案
类型断言会帮助你。您可以指定在特定情况下要使用的类型。
function doSomething( animal: Animal ) {
if((animal as Dog).breed) {
// do something doglike.....
}
}
推荐阅读
- javascript - Storybook 为单个故事预定义的视口/参数
- cmake - 如何复制cmake目标
- php - WordPress | 转换#038; 至 &
- angular - 角度地理位置变空
- mysql - MySQL/MariaDB 在列表中找到一个或多个数字,将彩票号码与过去的结果匹配
- python - 如何合并 2 个字典列表,以便始终替换具有 None 值的键(如果不存在 None 值)
- html - 如何根据设备更改按钮大小?
- javascript - ReactJS - 在同一个 div 中更新组件(从列表生成)
- javascript - 检查输入表单需要两次点击才能验证
- android - 从 Firebase 子值读取的 Android Spinner 选定值