In TypeScript, type aliases are used to assign a name for any type. It doesn't create a new type. Instead, it provides a name for the type.
To create a type alias, we need to use the type
keyword.
type gender = "male" | "female" | "nonbinary";let male:gender = "male";let female:gender = "female";let nonbinary:gender = "nonbinary";console.log(male, female, nonbinary)
In the code above, we have created a type alias with the name gender
. The gender
type can have one of the following values: "male"
, "female"
, or "nonbinary"
.
When we try to assign a value other than the configured value, we get a compilation error. The code widget below demonstrates this case:
type gender = "male" | "female" | "nonbinary";// assigning value which is not configured will throw compilation errorlet err:gender = "gen";
type alphaNumeric = string | number;let num:alphaNumeric = 10;let str:alphaNumeric = "ten";type Point = {x: number;y: number;};let pt:Point = {x: 10, y: 20};// obj type variable can have any one of the below valuetype obj = {val: 1} | {val: 2};// obj type variable can have any one of the below valuetype func = (() => string) | (() => void);
alphaNumeric
. The alphaNumeric
type can have either a string or a numeric value.Point
. The Point
type is an object that has two numeric properties, x
and y
.obj
. The value of the obj
type should either be {val: 1}
or {val: 2}
. Similarly, we create a type for func
in line 17.