-
Notifications
You must be signed in to change notification settings - Fork 0
/
unionTypes.ts
49 lines (41 loc) · 1.21 KB
/
unionTypes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");
// Error
// printId({ myID: 22342 });
function printId2(id: number | string) {
if (typeof id === "string") {
// In this branch, id is of type 'string'
console.log(id.toUpperCase());
} else {
// Here, id is of type 'number'
console.log(id);
}
}
printId2('Hello0001'); //HELLO0001
printId2(2002); //2002
function welcomePeople(x: string[] | string) {
if (Array.isArray(x)) {
// Here: 'x' is 'string[]'
console.log("Hello, " + x.join(" and "));
} else {
// Here: 'x' is 'string'
console.log("Welcome lone traveler " + x);
}
}
welcomePeople(['Vinidu', 'Vimukthi', 'Nipun']); //Hello, Vinidu and Vimukthi and Nipun
welcomePeople('Dinil'); //Welcome lone traveler Dinil
// let data: number[] | boolean[] = [10, 20, true, false];
let data: (number | boolean)[] = [10, 20, true, false];
//----------------------------------------------------
// strict union
function windowStatus(status: "open" | "close"){
console.log('Window is ' + status);
}
windowStatus("open");
windowStatus("close");
// windowStatus("hello"); //Illegal