首页 > 解决方案 > 打字稿,联合类型,元素隐含一个“任何”

问题描述

我有下一种情况,这里有几个接口和类型:

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'

怎么了?

标签: javascripttypescriptfrontendtypescript-typings

解决方案


问题是接口author上不存在该字段,因此如果is a和is则可能是无效字段。一种解决方案是确保两个接口都包含相同的字段:Magazinex[filter.field]xMagazinefield"author"

interface Book {
  id: number;
  title: string;
  author: string;
  pageCount?: undefined;
}

interface Magazine {
  id: number;
  title: string;
  pageCount: string;
  author?: undefined;
}

推荐阅读