Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning an object which has keys as the values of passed array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading