Skip to content

Commit 6898f10

Browse files
committed
Typeguard in TS
1 parent 452d139 commit 6898f10

2 files changed

Lines changed: 49 additions & 10 deletions

File tree

typescript-masterclass/README.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,3 +264,32 @@ const item: Record<keyof TrackStates, string> = {
264264
//Number are coerced to string
265265
dictionary[0] = item;
266266
```
267+
268+
### Typeguard in TS
269+
270+
```ts
271+
class Song {
272+
constructor(public title: string, public duration: string | number) {}
273+
}
274+
275+
function getSongDuration(item: Song) {
276+
if (typeof item.duration === "string") {
277+
return item.duration;
278+
}
279+
const { duration } = item;
280+
const minutes = Math.floor(duration / 60000);
281+
const seconds = (duration / 1000) % 60;
282+
return `${minutes}:${seconds}`;
283+
}
284+
285+
const songDurationFromString = getSongDuration(
286+
new Song("Wonderful Wonderful", "05:30")
287+
);
288+
console.log(songDurationFromString);
289+
290+
const songDurationFromMS = getSongDuration(
291+
new Song("Wonderful Wonderful", 330000)
292+
);
293+
294+
console.log(songDurationFromMS);
295+
```

typescript-masterclass/src/app.ts

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,24 @@
1-
let dictionary: Record<string, TrackStates> = {};
1+
class Song {
2+
constructor(public title: string, public duration: string | number) {}
3+
}
24

3-
interface TrackStates {
4-
current: string;
5-
next: string;
5+
function getSongDuration(item: Song) {
6+
if (typeof item.duration === "string") {
7+
return item.duration;
8+
}
9+
const { duration } = item;
10+
const minutes = Math.floor(duration / 60000);
11+
const seconds = (duration / 1000) % 60;
12+
return `${minutes}:${seconds}`;
613
}
714

8-
const item: Record<keyof TrackStates, string> = {
9-
current: "abc23ds",
10-
next: "dsfsdflink3",
11-
};
15+
const songDurationFromString = getSongDuration(
16+
new Song("Wonderful Wonderful", "05:30")
17+
);
18+
console.log(songDurationFromString);
19+
20+
const songDurationFromMS = getSongDuration(
21+
new Song("Wonderful Wonderful", 330000)
22+
);
1223

13-
//Number are coerced to string
14-
dictionary[0] = item;
24+
console.log(songDurationFromMS);

0 commit comments

Comments
 (0)