Typescript String, Boolean, Number & Enum Literal types

TypeScript Literal Types restrict the value of a variable to finite valid values. The latest version of Typescript supports the following Literal Types

  1. String Literal Types
  2. Numeric Literal Types
  3. Boolean Literal Types
  4. Enum Literal Types

This is very useful feature which restrict the possible values, that you can store in a variable

String Literal Types

The String Literal types accept only pre defined string value.

In the following example engineStatus can have only one value i.e. "Active"

Defining a variable type as string literal does not initialize its value. The TypeScript initializes the variable as Undefined.

We can only assign the value "Active" to it.

Union Types

The power of literal types comes, when you create the Union Types using string literal types

The engineMode variable can now only have two literal types"started"& "stopped". Any other values including the values who only change in a case like "Started" is also not allowed.

Using literal types stops the users from mistyping the value of a variable. Also it gives you intellisense help as shown below.

Numeric Literal Types

The numeric literal types works similar to the string literal types

The following example creates a numeric literal type with value 1. You can only assign 1 to it. Assigning any other value other that 1 results in a compile error.

Use union types to restrict the values that a variable can take.

Perform Numerical operations.

You can assign it to a number, but not other way around

Boolean Literal Types

Boolean Literal Types works in a similar way.

Enum Literal Types

You can also define Enum as literal type.

Literal Types

The following examples uses the union of string, number & boolean literal types as the argument to engine function

References

Advanced Types

Scroll to Top