Javascript Typescript、联合类型、元素隐式地具有一个';任何';
我有下一种情况,这里有几个接口和类型:Javascript Typescript、联合类型、元素隐式地具有一个';任何';,javascript,typescript,frontend,typescript-typings,Javascript,Typescript,Frontend,Typescript Typings,我有下一种情况,这里有几个接口和类型: interface Book { id: number; title: string; author: string; } interface Magazine { id: number; title: string; pageCount: string; } type Publication = Book | Magazine; type BookFields = keyof Book; type MagazineField
interface Book {
id: number;
title: string;
author: string;
}
interface Magazine {
id: number;
title: string;
pageCount: string;
}
type Publication = Book | Magazine;
type BookFields = keyof Book;
type MagazineFields = keyof Magazine;
type PublicationFields = BookFields | MagazineFields;
interface Filter {
field: PublicationFields;
}
我为每个实体使用不同的react组件,并希望具有通用排序功能,例如:
function publicationSort (publications: Array<Publication>, filter: Filter){
return publications.sort((x, y) => {
const firstVal = x[filter.field];
const secondVal = y[filter.field];
//Some lexical or number sort
})
}
函数publicationSort(发布:数组,筛选器:筛选器){
返回出版物。排序((x,y)=>{
常量firstVal=x[过滤器字段];
const secondVal=y[filter.field];
//一些词汇或数字排序
})
}
问题是:我希望调用x[filter.field]时会得到给定出版物的值,例如,我在sort函数中传递一本书,并希望它的工作方式类似于const firstVal=book[author]
,取而代之的是错误:元素隐式地具有“any”类型,因为“PublicationFields”类型的表达式不能用于索引类型“Publication”。类型“Publication”上不存在属性“author”
有什么问题?问题是
杂志
界面上不存在作者
字段,因此x[filter.field]
可能是无效字段,如果x
是杂志
而字段
是作者
。一种解决方案是确保两个接口包含相同的字段:
interface Book {
id: number;
title: string;
author: string;
pageCount?: undefined;
}
interface Magazine {
id: number;
title: string;
pageCount: string;
author?: undefined;
}