将具有公共基接口的泛型Typescript数组声明为类型
我想声明一个具有公共基接口的项数组,但不知道如何声明 我有一个基本接口和几个扩展基本接口的子接口:将具有公共基接口的泛型Typescript数组声明为类型,typescript,typescript-generics,Typescript,Typescript Generics,我想声明一个具有公共基接口的项数组,但不知道如何声明 我有一个基本接口和几个扩展基本接口的子接口: interface Animal { name: string; birthdate: Date; } interface Bird extends Animal { featherColor: string; } interface Dog extends Animal { furColor: string; } 我想这样做: interface AnimalList {
interface Animal {
name: string;
birthdate: Date;
}
interface Bird extends Animal {
featherColor: string;
}
interface Dog extends Animal {
furColor: string;
}
我想这样做:
interface AnimalList {
animals: Array<? extends Animal>
}
// define an example
const list: AnimalList = {
animals: [
{name: 'Bobby', birthdate: new Date(), furColor: 'brown'},
{name: 'Bobby', birthdate: new Date(), featherColor: 'green'},
]
}
您有两个选择:
界面动物{
名称:字符串;
出生日期:日期;
}
鸟类与动物的接口{
羽毛颜色:弦;
}
接口狗扩展了动物{
furColor:字符串;
}
界面动物学家{
动物:阵列
}
常量列表=(arg:AnimalList)=>arg
/**
*FISR,接受所有扩展动物的类型
*/
常量结果=列表({
动物:[
{name:'Bobby',生日:new Date(),furColor:'brown'},
{姓名:'Bobby',出生日期:new Date(),羽毛颜色:'green'},
]
})
/**
*其次,如果您想定义预先允许的类型
*/
常数列表2:动物学家={
动物:[
{name:'Bobby',生日:new Date(),furColor:'brown'},
{姓名:'Bobby',出生日期:new Date(),羽毛颜色:'green'},
]
}
如您所见,您可以使用函数来推断类型,也可以使用union类型
更新
至于第二种方法
正如您可能已经注意到的,您无法添加既不是鸟也不是狗的动物
const list 2:AnimalList={
动物:[
{name:'Bobby',生日:new Date(),furColor:'brown'},
{姓名:'Bobby',出生日期:new Date(),羽毛颜色:'green'},
{name:'Bobby',生日:new Date(),fname:'green'},//错误
]
}
如果要从阵列中过滤鸟类,可以使用typeguards:
const isBird=(动物:动物):动物就是鸟=>
Object.prototype.hasOwnProperty.call(动物,'featherColor')
const getAnimals=list2.animals.filter(isBird)//Bird[]
我不清楚你的意思
关于可维护性,坏习惯,不是吗
这是我的第一个方法,是的。但这将产生一个
TS2322:Type“{name:string;birthdate:Date;furColor:string;}”不能分配给类型“Animal”。Object literal只能指定已知属性,而“furColor”在类型“Animal”中不存在。
第二种方法是,关于可维护性,坏习惯,不是吗?它确实可以工作,但是如果有很多不同的接口,而不是两个或三个,那么它似乎很容易出错。然而,我不明白列表
做了什么-它似乎是多余的?@letmejustfix我做了一个update@letmejustfixthat在这种特殊情况下,列表
是多余的。我只是想向你们展示不同的方法。
TS2322: Type '{ name: string; birthdate: Date; furColor: string; }' is not assignable to type 'Animal'.
Object literal may only specify known properties, and 'furColor' does not exist in type 'Animal'.