I would like my function to return an object which has the key of the passed in array parameter’s values.
If user passes the array ["i","love","potato"], then I want the return type to be inferred as { i: string; love: string; potato: string }. How can I achieve this?
Here is my attempt:
public async getParameters(keys: readonly string[]): Promise<{ [K in typeof keys]: string }> {...}
>Solution :
I am making a few assumptions here, looking at the code, it looks like you are writing a function in TS where you want to map over the types of an array and then produce a new object with the keys based on the values in the array.
Your method wont work, here is the correct way of going about it:
public async getParameters<T extends string[]>(keys: readonly [...T]): Promise<{ [K in T[number]]: string }> {
const result: any = {};
for (const key of keys) {
result[key] = "";
}
return result;
}
const obj = await getParameters(["i", "love", "potato"]);