Skip to content

Commit dce3298

Browse files
committed
Union in TS
1 parent 9d8e804 commit dce3298

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

TS/Basics/union.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// UNION (|)
2+
3+
let score: number|string = 33
4+
score = "55"
5+
6+
type User = {
7+
userName: string,
8+
isActive: boolean
9+
}
10+
11+
type Admin = {
12+
name: string,
13+
id: number;
14+
}
15+
16+
let account: User | Admin = {userName: "Spidey", isActive: true}
17+
account = {name: "Peter", id: 342}
18+
19+
// function getDBId(id: number | string){
20+
// // Making some api calls
21+
// console.log(`DB Id: ${id}`);
22+
// }
23+
24+
getDBId(3);
25+
getDBId("67");
26+
27+
function getDBId(id: number | string){
28+
29+
if (typeof id === "string") {
30+
id = id.toLowerCase();
31+
}
32+
33+
else if (typeof id === "number") {
34+
id = id+2;
35+
}
36+
37+
// Making some api calls
38+
console.log(`DB Id: ${id}`);
39+
}
40+
41+
// Array
42+
const data: (number | string)[] = [1, 2, 3, 4, "5"]; // Either be all numbers or all strings
43+
44+
// Literal Assignment
45+
const pi:3.14 = 3.14 // cannot be assigned to any other number
46+
47+
let seatAllotment: "aisle" | "middle " | "window"
48+
seatAllotment = "aisle"
49+
// seatAllotment= "crew"

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy