Custom type

In Typescript, you are able to come up with your own type if you need to, by using the type keyword in the following way:

type Animal = 'Cheetah' | 'Lion';

What we have created now is a type with x number of allowed values. Let's create a variable from this type:

var animal: Animal = 'Cheetah';

This is perfectly allowed as Cheetah is one of the allowed values, and works as intended. The interesting part happens when we give our variable a value it does not expect:

var animal: Animal = 'Turtle';

This results in the following compiler error:

error TS2322: Type '"Turtle"' is not assignable to type 'Animal'.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset