代码之家  ›  专栏  ›  技术社区  ›  user1713450

如何在TypeScript中定义一个具有已定义属性和索引“回退”的类型

  •  0
  • user1713450  · 技术社区  · 4 年前

    用例:我正在从远程API接收数据。数据是动态生成的,有时会发生变化。我知道我将收到的类型是一个对象数组,每个对象至少包含名为“value”和“description”的属性

    interface Item {
      value: string
      description: string
    }
    type Response = Item[]
    

    然而,响应还将包含其他未知数据。我将编写一个函数,通过修剪所有不符合以下条件之一的属性来规范化这些数据:

    1. 属性指数是“价值”
    2. 属性索引是“描述”
    3. 财产 价值 属于类型 Item[] (在我的应用程序编译时不知道属性索引)
    interface IncomingItem {
      value: string
      description: string
      [index:string]: unknown
    }
    
    interface NormalizedItem {
      value: string
      description: string
      [index:string]: NormalizedItem[]
    
    declare const normalizeItem : (i:IncomingItem) => OutgoingItem
    declare const items: IncomingItem[]
    const normalizeItems = items.map(normalizeItem) //NormalizedItem[]
    

    我似乎找不到办法。我尝试了上述类型,但索引类型不能不是已定义属性的类型。

    然后我尝试了这个,这是一个有效的类型,但你不能将数据分配给这个类型:

    type NormalizedType = {
      value:string
      description:string
    } & {[index:string]:NormalizedType[]}
    
    declare const getOnlyIncomingTypeArrays : (i:IncomingType) => {[index:string]:IncomingType[]}
    
    const normalize = (i:IncomingType):NormalizedType => ({
      value: i.value,
      description: i.description,
      ...normalize(getOnlyIncomingTypeArrays(i)),
    })
    

    但您不能分配给 NormalizedType 而不会出现TS错误。

    0 回复  |  直到 4 年前