Deep dive into enums, const assertions and union types

Enums

String enums

enum Direction {   Up = "UP",   Down = "DOWN"}
var Direction;(function (Direction) {Direction["Up"] = "UP";Direction["Down"] = "DOWN";})(Direction || (Direction = {}));
enum Direction {    Left = "LEFT"}
processDirection("UP") // Type error

Structural and nominal typing

Numeric enums

enum FileMode {   Read,   Write,   ReadWrite}
var FileMode;(function (FileMode) {    FileMode[FileMode["Read"] = 0] = "Read";    FileMode[FileMode["Write"] = 1] = "Write";    FileMode[FileMode["ReadWrite"] = 2] = "ReadWrite";})(FileMode || (FileMode = {}));
enum FileMode {  Read = 1,  Write,  ReadWrite}
(function (FileMode) {    FileMode[FileMode["Read"] = 1] = "Read";    FileMode[FileMode["Write"] = 2] = "Write";    FileMode[FileMode["ReadWrite"] = 3] = "ReadWrite";})(FileMode || (FileMode = {}));
enum ShirtSize {  XS = 28,  S = 30,  M = 32,  L = 34}
function calculatePrice(size: ShirtSize, basePrice: number) {     const priceMultiplierMap = {        [ShirtSize.XS]: 1,        [ShirtSize.S]: 1.5,        [ShirtSize.M]: 2.1,        [ShirtSize.L]: 2.5     }     return basePrice * priceMultiplierMap[size];}calculatePrice(ShirtSize.M, 35.5) 
// This is type safe and produces correct output as 74.55
calculatePrice(20, 44)

Const enums

const enum Directions {   Up = "UP",   Down = "DOWN"}const currentDirection = Direction.Up;
const currentDirection = "UP" /* Up */;
  • The compiler reads a module
  • The module’s type information is stripped
  • The remaining is written as the JavaScript file.

Const assertions

Widening literal types

let fileName = "const-assertions.md";
let fileName = "const-assertions.md";
fileName = "typescript.md"; // No type error
fileName = 15;
// Type error - Type 'number' is not assignable to type 'string'
let isAuthenticated = false; // Type - booleanlet itemsInCart = 12; // Type - number
const userName = "Aishwarya"

Non-widening literal types

const currentDay = "Sunday"; // Type : "Sunday"let newCurrentDay = currentDay; // Type: string
const currentDay = "Sunday" as const;let newCurrentDay = currentDay; // Type: SundaynewCurrentDay = "Monday"; // Error: Type '"Monday"' is not assignable to type '"Sunday"'.
const HEADING_LEVEL_1 = "h1" as const;const HEADING_LEVEL_2 = "h2" as const;const allowedLevels = [HEADING_LEVEL_1, HEADING_LEVEL_2]; 
// Type: ("h1" | "h2")[]
allowedLevels.push("h3")
// Error: Argument of type '"h3"' is not assignable to parameter of type '"h1" | "h2"'
const Direction = {   Up: "UP",   Down: "DOWN"}
const Direction = {   Up: string;   Down: string;}
Direction.Up = "New Up"Direction.Down = "New Down"
const Direction = {   Up: "UP" as "UP",   Down: "DOWN" as "DOWN"}
// Typeconst Direction = {  Up: "UP",  Down: "DOWN"}
const Direction = {   Up: "UP",   Down: "DOWN"} as const
const Direction: {  readonly Up: "UP";  readonly Down: "DOWN";}
type DirectionType = typeof Direction[keyof typeof Direction]
type DirectionType = "UP" | "DOWN"
Object.keys(Direction).map((key) => Direction[key]) 
// Outputs ["UP" | "DOWN" ]
type Values<ObjectLiteral> = ObjectLiteral[keyof ObjectLiteral];const Direction = {   Up: "UP",   Down: "DOWN"} as const;type DirectionType = Values<typeof Direction>;function processDirection(direction: DirectionType) {    /**  Code */   return callbacksMap[direction];}

Union types

type Direction = "UP" | "DOWN";function processDirection(direction: Direction) {   /**  Code */   return callbacksMap[direction];}processDirection("UP");// For numberstype ShirtSize = 28 | 30 | 32 | 34;

Conclusion

--

--

--

Fullstack developer at Unite

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What is ng-template, ng-container, ng-content in Angular?

BlogPost_401

Connecting to a server-side API through Google Cloud Functions for Firebase

Photo by Laura Vinck on Unsplash

Outlook Add-in — Office.js + Angular + Validate Sender email address

VS Code not recognizing HTML?

Javascript Execution Context, Hoisting, Scope, Scope Chain, and Closures Deep Dive.

Using React Hooks, useEffect to Make Reoccurring API Calls

Not All CPaaS Are Created Equal

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aishwaryalakshmi Panneerselvam

Aishwaryalakshmi Panneerselvam

Fullstack developer at Unite

More from Medium

The Structure of Conditional Expressions

Forever Functional #13: Shuffling an Array

How to base your output type on a generic input type in typescript

Two persons writing on a whiteboard