Skip to content

Commit 47e4eda

Browse files
committed
User-Defined TypeGuard
1 parent 2d8dd08 commit 47e4eda

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

typescript-masterclass/README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,3 +332,46 @@ const playlistName = getItemName(
332332

333333
console.log("Playlist Name :", playlistName);
334334
```
335+
336+
### User-Defined TypeGuard
337+
338+
```ts
339+
class Foo {
340+
bar() {}
341+
}
342+
343+
const bar = new Foo();
344+
345+
console.log(bar);
346+
347+
// console.log(bar instanceof Foo);
348+
// console.log(Object.getPrototypeOf(bar) === Foo.prototype);
349+
350+
class Song {
351+
constructor(public title: string, public duration: number) {}
352+
}
353+
354+
class Playlist {
355+
constructor(public name: string, public songs: Song[]) {}
356+
}
357+
358+
function isSong(item: any): item is Song {
359+
return item instanceof Song;
360+
}
361+
362+
function getItemName(item: Song | Playlist) {
363+
if (isSong(item)) {
364+
return item.title;
365+
}
366+
return item.name;
367+
}
368+
369+
const songName = getItemName(new Song("wonderful wonderful", 300000));
370+
console.log("Song Name :", songName);
371+
372+
const playlistName = getItemName(
373+
new Playlist("The Best Songs", [new Song("The Man", 30000)])
374+
);
375+
376+
console.log("Playlist Name :", playlistName);
377+
```

typescript-masterclass/src/app.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,12 @@ class Playlist {
1717
constructor(public name: string, public songs: Song[]) {}
1818
}
1919

20+
function isSong(item: any): item is Song {
21+
return item instanceof Song;
22+
}
23+
2024
function getItemName(item: Song | Playlist) {
21-
if (item instanceof Song) {
25+
if (isSong(item)) {
2226
return item.title;
2327
}
2428
return item.name;

0 commit comments

Comments
 (0)