typescript union type check code example

Example 1: union value typescript

let myVar : string | number;        //Variable with union type declaration
 
myVar = 100;            //OK
myVar = 'Lokesh';       //OK
 
myVar = true;           //Error - boolean not allowed

Example 2: typescript union types

type Cow = {
  name: string;
  moo: () => void;
};

type Dog = {
  name: string;
  bark: () => void;
};

type Cat = {
  name: string;
  meow: () => void;
};

// union type
type Animals = Cow | Dog | Cat;

Example 3: type gurad

1) Type guards narrow down the type of a variable within a conditional block.
2) Use the 'typeof' and 'instanceof operators to implement type guards in the
	conditional blocks.
   
//example(typeof)
if (typeof a === 'number' && typeof b === 'number') {
    return a + b;
}

(instanceof)
if (job instanceof detail){
	jobless = false ;
}

Tags:

Misc Example