1

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
goju
  • 25
  • 5
  • [This code](https://tsplay.dev/weXMdW) would resolve the issue as asked; I've closed this as a duplicate of other questions with the same error message. If you don't think this is a duplicate, please [edit] the question to show why the answers to the other questions don't apply. Good luck! – jcalz May 30 '22 at 19:38
  • to think of, this kinda answer and not, because, all of answer that have been posted in other question showing on how to use keyof, or Union type of string, instead i curious on how one string can be a Type generic for return value ( on how to grab one string alone ) but again, thank you for the answer – goju May 31 '22 at 06:59

0 Answers0