Skip to content Skip to sidebar Skip to footer

Typescript Strong Typing - Specifying Object Value Types

In TypeScript, is it possible to specify allowed values in an Object? E.g. to specify that all keys should have numbers: { 'id': 1, 'attr1': 124, 'attr2': 4356, ... } ? I'

Solution 1:

is it possible to specify allowed values in an Object? E.g. to specify that all keys should have numbers

Yes, this is possible.

In both JavaScript & TypeScript (which is a superset of JS) you can access properties via obj.prop or obj['prop'] which is what allows the syntax below to work.

// This defines an interface that only allows values to be numbersinterface INumbersOnly {
  [key: string]: number;
}

// when using it, it will check that all properties are numbersvarx: INumbersOnly = {
  num: 1, // works finestr: 'x'// will give a type error
};

Above example in TS Playground

Post a Comment for "Typescript Strong Typing - Specifying Object Value Types"