1type Cow = {
2 name: string;
3 moo: () => void;
4};
5
6type Dog = {
7 name: string;
8 bark: () => void;
9};
10
11type Cat = {
12 name: string;
13 meow: () => void;
14};
15
16// union type
17type Animals = Cow | Dog | Cat;
18
1let myVar : string | number; //Variable with union type declaration
2
3myVar = 100; //OK
4myVar = 'Lokesh'; //OK
5
6myVar = true; //Error - boolean not allowed
7
1// Union Type: function reacts depending on x type (array of string OR string)
2function welcomePeople(x: string[] | string) {
3 if (Array.isArray(x)) {
4 console.log("Hello, " + x.join(" and ")); // 'x' is 'string[]'
5 } else {
6 console.log("Welcome lone traveler " + x); // 'x' is 'string'
7 }
8}