O'Reilly logo

Cross-platform Desktop Application Development: Electron, Node, NW.js, and React by Dmitry Sheiko

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Enum type

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required