Home > Software design >  Typescript type for object-key to not start with specific character
Typescript type for object-key to not start with specific character

Time:08-11

In typescript you can force all keys in an object type to start with a certain character:

type A = {
    [key: `@${string}`]: number
}
// okay:
const a1: A = {
  '@aaa': 10
}
// error:
const a2: A = {
  'aaa': 10
}

how do I do the opposite? I don't want my keys to start with @, like this:

type A = {
    [key: ????]: number
}
// error:
const a1: A = {
  '@aaa': 10
}
// okay:
const a2: A = {
  'aaa': 10
}

CodePudding user response:

You can create a union type that enables this behavior.

The first type simply defines an object where the key can be any string:

{ [k: string]: number }

For the second type, we can exclude keys that begin with "@" by indicating that they may be present, but using the "never" type to make assignment impossible:

{ [K in `@${string}`]?: never }

The resulting type definition would look like this:

type A = { [k: string]: number } & { [K in `@${string}`]?: never }

// error:
const a1: A = {
   '@aaa': 10
}

// okay:
const a2: A = {
   'aaa': 10
}
  • Related