Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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've searched through http://www.typescriptlang.org/Handbook and found out, that I can use Array typing (both keys and values) like this:

interface StringArray {
  [index: number]: string;
}

but actually, a Map (JS Object) and an Array is not the same, conceptually (in JavaScript, it behaves similarly, but in TypeScript, it should be treated separately because of the strong typing).

like image 273
ducin Avatar asked Feb 09 '23 07:02

ducin


1 Answers

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 numbers
interface INumbersOnly {
  [key: string]: number;
}

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

Above example in TS Playground

like image 77
Brocco Avatar answered Feb 12 '23 01:02

Brocco