In TypeScript, we need to specify data types for variables.
let a:string;
We might come across a situation where the data can be of different data types, depending upon the situation.
For example, if we want to store string
and boolean
in variable a
, then we use TypeScript union
.
You can combine different data types.
Use the pipe |
operator to separate data types.
let variableName:datatype 1| datatype 2 | ... | datatype n
In the code snippet below:
We create variable a
with types string
and boolean
.
In line 2, we assign the value John
, which is of string type, to a
.
In line 3, we assign true
, which is of boolean
type, to a
.
let a:string | boolean;a = "John"console.log(a)a = trueconsole.log(a)
The compiler will throw an error if we assign values of types other than the specified data types.
In the following code snippet, we assign value 1
, which is of number
type, to a
.
Type '1' is not assignable to type 'string | boolean'
.let a:string | boolean;a = "John"a = true//will throw errora = 1
We can create custom types using TypeScript unions and type
keywords so that we can assign new custom types to different variables.
In the code snippet below:
We create a customType
that represents data types string
, number
, and boolean
.
In lines 3 and 4, we create variables a
and b
with the type customType
.
// creating custom type usign uniontype customType = (string | number | boolean);//assigning custom typelet a:customType;let b:customType;a = 5console.log(a)a = "John"console.log(a)a = trueconsole.log(a)b = 10console.log(b)