Home > Software engineering >  How can I make a typescript type where all keys in object have same prefix?
How can I make a typescript type where all keys in object have same prefix?

Time:03-14

I'm looking to create a object type UiPrefixed where all the keys in the object have to be prefixed with /^ui\:. /, is this possible?

type UiPrefixed = {
  [`ui:*`]: any
}

const e: UiPrefixed = {
  'ui:meow': true,
  'ui:woof': true
}

CodePudding user response:

Yes. This is one of the scenarios where template literal types can come in handy: ui:${string}:

type UiPrefixed = {
  [key: `ui:${string}`]: any
}

const e: UiPrefixed = {
  'ui:meow': true,
  'ui:woof': true
}

See proof-of-concept on TypeScript Playground.

  • Related