Typescript String, Boolean, Number & Enum Literal types

TypeScript Literal Types restrict the value of a variable to finite valid values. This is in contrast to the variable which allows you to change value (except for TypeScript Constants). The latest version of Typescript supports the String Literal Types, Numeric Literal Types, Boolean Literal Types & Enum Literal Types

What is a Literal

A literal is a notation for representing a fixed value in the source code. For Example, 1 is literal, because it represents the number 1. hello is literal because it represents the string “hello”. Similarly null is literal because it represents the value null.

This is exactly opposite to TypeScript variables or TypeScript constants, which can take any value.

TypeScript also allows us to define our own literal types. 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 a very useful feature that restricts the possible values, that you can store in a variable

String Literal Types

The String Literal types accept only pre-defined string values.

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

Defining a variable type as a 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 that 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 work similarly to the string literal types

The following example creates a numeric literal type with a 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 vice versa

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

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top