Marek Krzeminski
Marek Krzeminski

Reputation: 1398

Typescript: How to add type safety to object properties?

I have the following:

type CommandTypes = 'one' | 'two' | 'three';
const CONST = {
  commands: {
    a: 'one',
    b: 'two',
    c: 'error'
  },
};

Is there a way to enforce that all the commands are of a particular type?

Right now TypeScript is telling me that a, b, and c are of type string, but I want to enforce those properties to be of type CommandTypes so that a developer can not specify an arbitrary string. I want TypeScript to be able to catch the error that c is invalid since it doesn't belong to the CommandTypes that are allowed.

If I break up the CONST definition this way:

type CommandTypes = 'one' | 'two' | 'three';
const commands : CommandTypes = {
  a: 'one',
  b: 'two',
  c: 'error'
}

const CONST = {
  commands,
};

Then this does in fact catch the error with c, however now I also lose auto completion in Visual Studio code. If I type CONST.commands. I don't get any auto completion here now, where as if I leave the definition as shown at the top of the post, then I do get auto completion.

Upvotes: 0

Views: 532

Answers (1)

Shanon Jackson
Shanon Jackson

Reputation: 6571

Record<CommandTypes, string> will give you a object who's keys are the distributed union of CommandType and the values have to be strings. Note: you can only have a single type on the right hand side if you want different types for each key you will have to read typescripts documentation on mapped types

Upvotes: 1

Related Questions