javascript - 打字稿,联合类型,元素隐含一个“任何”
问题描述
我有下一种情况,这里有几个接口和类型:
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;
}
我为每个实体使用不同的反应组件,并希望具有通用的排序功能,例如:
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
})
}
问题是:我希望当调用 x[filter.field] 时会获得给定出版物的值,例如,我在排序函数中传递一本书并期望它会像 一样工作const firstVal = book[author]
,而不是我得到错误:Element implicitly has an 'any' type because expression of type 'PublicationFields' can't be used to index type 'Publication'. Property 'author' does not exist on type 'Publication'
怎么了?
解决方案
问题是接口author
上不存在该字段,因此如果is a和is则可能是无效字段。一种解决方案是确保两个接口都包含相同的字段:Magazine
x[filter.field]
x
Magazine
field
"author"
interface Book {
id: number;
title: string;
author: string;
pageCount?: undefined;
}
interface Magazine {
id: number;
title: string;
pageCount: string;
author?: undefined;
}
推荐阅读
- outlook - 无法更新 Outlook 2016 msi 安装程序以支持 Office.js 要求集 1.4
- .htaccess - .htaccess 重定向循环与 RewriteCond
- c# - 当我尝试提交表单以将一些值和上传图像的路径存储到数据库中时,我收到一个错误,因为 [未设置对象引用 ....]
- reportlab - 从 ReportLab 中的表格行中删除圆角边框
- java - EndPoint 类中的 Spring WS SOAP 响应头修改
- mysql - 从表中删除记录取决于其他表值
- ionic-framework - Ionic 4 中的 CSS 变量
- reactjs - 如何访问 getDerivedStateFromProps 中的组件函数
- openpai - 概念Job和Framework的区别和关系
- cesium - 在 cesium 中,如何随时间动态更新标签?