1
type Test<T extends string, V extends unknown> = {
  [Key: T]: V;
}

type Test<T extends string, V extends unknown> = {
  [Key in T]: V;
}

From the code above, T extends string,why T can not be used as Key's type and it output an error An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead. But if replace Key: T with Key in T, it works.

ChenLee
  • 1,371
  • 3
  • 15
  • 33
  • try doing the property optional, it may help, see https://stackoverflow.com/a/64694571/17239546 – Mykyta Halchenko Apr 15 '22 at 10:25
  • The top one is an index signature and the bottom one is a mapped type; they look similar but are distinct. See the answer to the linked question. – jcalz Apr 15 '22 at 14:15

1 Answers1

2

I think what you're looking for in TypeScript is called Utility Type - Record

For example:

type Test<T extends string, V extends unknown> = Record<T, V>;

Docs: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type

true_k
  • 344
  • 1
  • 9