In this particular case, you can utilize the type
keyword:
type myType = 'DEVELOPMENT' | 'PRODUCTION' | 'TEST'
class someClass {
// Accepts any value of myType
constructor(mode: myType ) { }
}
For more complex scenarios, refer to the TypeScript documentation snippet below, where K extends keyof T
ensures only specified object values are passed as function arguments:
function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] {
return names.map(n => o[n]);
}
interface Person {
name: string;
age: number;
}
let person: Person = {
name: 'Jarid',
age: 35
};
let strings: string[] = pluck(person, ['name']); // valid, returns string[]
This utility service can be used universally across multiple constructors where type safety is desired.
You can also encapsulate secure values in a separate class and use keyof
directly:
class A {
prop1: 1;
prop2: 2;
}
class TestClass {
constructor(key: keyof A) {
}
}
let tc1 = new TestClass('prop1')
let tc2 = new TestClass('whoops') // Results in an error
If you are looking for something similar to valueof
rather than keyof
, enums and types should be your focus.