July 2017
Intermediate to advanced
300 pages
5h 43m
English
Time after time, we use constants to define a set of logically related entities. With TypeScript, we can declare an enumerated type populated with immutable data and then refer to the whole set by the type:
const enum Status {
NEEDS_PATCH,
UP_TO_DATE,
NOT_INSTALLED
}
function setStatus( status: Status ) {
// ...
}
setStatus( Status.NEEDS_PATCH );
Here, we declare a type Status that accepts one of the predefined values (NEEDS_PATCH, UP_TO_DATE, and NOT_INSTALLED). The function setStatus expects the status parameter to be of the Status type. If you pass in any other value, TypeScript reports an error:
setStatus( "READY" ); // error TS2345: Argument of type '"READY"' is not assignable to parameter of type 'STATUS'.
Alternatively, ...
Read now
Unlock full access