【问题标题】:How to generically type a function that returns a value array of an object array?如何一般键入返回对象数组的值数组的函数?
【发布时间】:2021-06-10 04:23:40
【问题描述】:

我正在尝试键入一个函数,该函数返回一个通用对象数组的值数组(用于获取表的所有列值)。

class DataSource<T> {
  
  constructor(private data: T[]) {}

  public getColumnValues(column: keyof T): any[] { // this is the thing I don't know how to type!
    return data.map(entry => entry[key]);
  }
}

目标是具有显示正确返回值的通用签名。例如:getColumnValues('someDate') 应为 Date[]getColumnValues('someString')string[]

我尝试搜索此内容,但我可能无法正确表达我的问题...

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    您需要将getColumnValues 设为泛型函数,以便类型可以基于特定属性,而不仅仅是T 的任何属性。我们将返回该键的属性数组。 K 是键,T[K] 是值,T[K][] 是值的数组。

    class DataSource<T> {
      
      constructor(private data: T[]) {}
    
      public getColumnValues<K extends keyof T>(column: K): T[K][] {
        return this.data.map(entry => entry[column]);
      }
    }
    

    Typescript 能够在您调用函数时推断出K,因此它会返回正确的类型。

    const mySource = new DataSource([{id: 1, name: "John"}, {id: 2, name: "Susan"}]);
    
    const names = mySource.getColumnValues('name'); // type is string[]
    
    const ids = mySource.getColumnValues('id'); // type is number[]
    

    Typescript Playground Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      相关资源
      最近更新 更多