Home > Back-end >  Dynamic key in typescript type
Dynamic key in typescript type

Time:05-27

Suppose a type key has this format: XXX_{placeholder1}_{placeholder2} where placeholder1 could be a,b,c,...,z, same for placeholder2. Instead of explicitly defining

type ObjectT = {
  XXX_a_a: '...',
  XXX_a_b: '...',
  ....
  XXX_z_z: '...'
}

Is there any way I could dynamically generate those keys? I know I could use

type ObjectT = {
  [key: string]: string
}

But it's too generate, and I want a more restricted type

CodePudding user response:

Yes, you can use template literal types !

type az = 'a' | 'b' | 'c' | ... | 'z'

type keys = `XXX_${az}_${az}`;

type ObjectT = Record<keys,string>

Playground

  • Related