I am currently working on developing a function in Typescript that maps an array of string values to a generic type. Each value in the array corresponds to a key in the object with the same index. For example:
Let's consider an interface called Person
interface Person {
lastName: string;
firstName: string;
}
We have an array of values
const values = ['foo', 'bar']
The expected outcome is an instance of Person
{
lastName: 'foo',
firstName: 'bar'
}
This function should be designed like this
const parse = <T extends Record<string, string | undefined>>(values: Array<string | undefined>)<T> => {
...
}
const result: Person = parse(['foo', 'bar']);
Merging 2 arrays into one object is not challenging, but defining the type for the returned generic can simplify things. Methods like Object.keys(T)
or for key in T
do not work well for obtaining the index of a key.
You can provide a generic with 100 properties and an array with only 5 values, where the first 5 properties will be assigned while the rest are null or undefined. Similarly, you can pass a generic with 3 properties and an array with 100 values, with only the initial 3 values being utilized. The array may include undefined or null