jeudi 23 septembre 2021

Map array of values to generic type in Typescript

I am trying to create a function to map array of string values to a generic type in Typescript. The index of the value in the array has the same index as the key in the object. For instance:

I have a Person interface

interface Person {
    lastName: string;
    firstName: string;
}

An array of values

const values = ['foo', 'bar']

And the desired result is an instance of Person

{
    lastName: 'foo',
    firstName: 'bar'
}

The desired function type should look like something like this

const parse = <T extends Record<string, string>>(values: string[])<T> => {
  ...
}

const result: Person = parse(['foo', 'bar']);

Mapping 2 arrays to one object is no problem but i want the typing of the returned generic to make things easier. Things like Object.keys(T) or for key in T does not work so it's hard to get an index of a key.





Aucun commentaire:

Enregistrer un commentaire