Home > Mobile >  Typing with enum field and a random string as key
Typing with enum field and a random string as key

Time:01-12

I have an enum like this

export enum Test {
  A = 'A',
  B = 'B',
  C = 'C'
}

I want a type that can have fields for each field of this enum A, B, C but also with the same fields concatenated with a string like 'A_2', 'B_2', 'C_2'

So for the A,B,C part I got this type

type TestExtended =  { [p in keyof typeof Test]: string } 

How can I complete it to get 'A_2', 'B_2', 'C_2' ?

CodePudding user response:

Maybe you can use something like this (the Partial is optional):

type TestExtended = Partial<Record<`${keyof typeof Test}_2`, string>>;

const testExtended: TestExtended = { A_2: 'foo' };

Or even like this:

type TestExtended<T extends string = ''> = Partial<Record<`${keyof typeof Test}${T}`, string>>;

const testExtended: TestExtended<'_2'> = { A_2: 'bar' };

CodePudding user response:

You can remap keys to be concatenated with _2:

type TestExtended =  { [P in keyof typeof Test as `${P}_2`]: string };
  • Related