Search code examples
typescript

Can map a string literal type as key name in typescript?


I'm wondering if could map a string literal type as a key in new type.

I tried but it's not right.

const a = {
  type: "key",
  actions: {
    a() {},
    b() {},
  },
} as const;

/* Map to
{
  key: {
    a() {},
    b() {},
  }
}
*/

type A = typeof a

type T = {
  A['type']: A['actions']
  // 'A' only refers to a type, but is being used as a value here.ts(2693)
}

Solution

  • You can like this:

    type T = {
      [K in A['type']]: A['actions']
    }
    
    

    TS Playground