i want to ask about how to grab string value from parameter to become a key in object transformation
ex:
function transformObject(
value, // <-- any, but for next example i will demonstrate as array
key // <-- string
) {
return { [key]: value };
}
hoping to get value like this
const foo = transformObject(['anyValue'], 'key']);
foo.key <-- autocomplete
// foo = {
// key: ['anyValue']
// }
so i come up with this idea to grab key as
function transformObject<T extends string>(
value: any,
key: T
): { [key: T]: string[] } {
return { [key]: value };
}
but it said
An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.ts(1337)
UPDATE:
already answered from the comment, meanwhile you can open the answer from comment, i also update here to show you on how the code should be
function transformObject<T extends string>(
value: string[],
key: T
) {
return { [key]: value } as { [key in T]: string[] };
}
const foo = transformObject(['anyValue'], 'key');
foo.key