Home > Blockchain >  How to infer keyof array's content in function call based on provided object
How to infer keyof array's content in function call based on provided object

Time:05-12

I would like to have Typescript predicting the type of my second argument in function doSomethingWithMyArray based on my input object provided on my first argument.

Example:

interface IPerson {
    name: string;
}
let myArr: IPerson[];


// should present a error 
doSomethingWithMyArray(myArr, 'key_of_element_in_array') 

// should be accepted
doSomethingWithMyArray(myArr, 'name') 


I tried this but clearly, keyof<T[]> doesn't work:

interface IPerson { name: string; }
const a: IPerson = {name: 'A'};
const b: IPerson = {name: 'B'};
const d: IPerson[] = [a,b];
type f = typeof a[];

function doSomethingWithMyArray<T>(arg1: T, arg2: keyof<T[]> ) {
  // do something....
}
// should predict 'name'
doSomethingWithMyArray(d, '');

CodePudding user response:

You can get the keys of T by using keyof T[number]:

function doSomethingWithMyArray<
  T extends any[]
>(arg1: T, arg2: keyof T[number] ) { }

You also have to constrain T to be an array with T extends any[]. Otherwise TypeScript will not allow the T[number] notation as T could be anything.

Playground

  • Related