t-MURO
t-MURO

Reputation: 671

How to generically type a function that returns a value array of an object array?

I'm trying to type a function that returns an array of values of a generic object array (used for getting all column values of a table).

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]);
  }
}

The goal is having a generic signature that shows the correct return value. For example: getColumnValues('someDate') should be Date[] or getColumnValues('someString') as string[]

I tried searching for this but I probably couldn't phrase my question properly...

Upvotes: 5

Views: 400

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42298

You need to make getColumnValues a generic function so that the type can be based on the specific property and not just any property of T. We will return an array of the properties for that key. K is the key, T[K] is the value, and T[K][] is the array of values.

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 is able to infer K when you call the function so it will return the right type.

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

Upvotes: 9

Related Questions