0

I would like to set the avaible values of a functions parameter something like this:

let valueList = [
   'val1',
   'val2',
   'val3',
];

let getSomething = (parameter: valueList) => {
    // do something
}

And i want to get error on console if parameter value other than what are in the valueList variable.

And it would be good, if IDE showup the possible values when I call the function as follow:

getSomething(| <- cursor ) // when cursor here, the IDE show the possible values from valueList
Twois
  • 548
  • 1
  • 7
  • 18
  • So you want an *enum*? – Andrew Li Jul 06 '17 at 13:37
  • Possible duplicate of [How to create enum like type in TypeScript?](https://stackoverflow.com/questions/12687793/how-to-create-enum-like-type-in-typescript) – Fabio Antunes Jul 06 '17 at 13:38
  • Possible duplicate of [How to document a string type in jsdoc with limited possible values](https://stackoverflow.com/questions/19093935/how-to-document-a-string-type-in-jsdoc-with-limited-possible-values) – skiilaa Jul 06 '17 at 13:53

2 Answers2

1

You can define an enum as mentioned in other answers or if you want your parameter to be a string, you can use a string literal type combined with union types:

type valueList = 'val1' | 'val2' | 'val3';


let getSomething = (parameter: valueList) => {
    // do something
}

getSomething("val1") // OK
getSomething("val1-wrong") // Error
Saravana
  • 37,852
  • 18
  • 100
  • 108
0

Use enum for this:

enum ValueList {
   val1,
   val2,
   val3
}
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84