Skip to content

Commit 01aa504

Browse files
committed
In-Operator & Littral-type in Type-Guard
1 parent 47e4eda commit 01aa504

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

typescript-masterclass/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,3 +375,48 @@ const playlistName = getItemName(
375375

376376
console.log("Playlist Name :", playlistName);
377377
```
378+
379+
### In-Operator & Littral-type in Type-Guard
380+
381+
```ts
382+
class Foo {
383+
bar() {}
384+
}
385+
386+
const bar = new Foo();
387+
388+
console.log(bar);
389+
390+
// console.log(bar instanceof Foo);
391+
// console.log(Object.getPrototypeOf(bar) === Foo.prototype);
392+
393+
class Song {
394+
kind: "song";
395+
constructor(public title: string, public duration: number) {}
396+
}
397+
398+
class Playlist {
399+
kind: "playlist";
400+
constructor(public name: string, public songs: Song[]) {}
401+
}
402+
403+
function isSong(item: any): item is Song {
404+
return "title" in item;
405+
}
406+
407+
function getItemName(item: Song | Playlist) {
408+
if (item.kind === "song") {
409+
return item.title;
410+
}
411+
return item.name;
412+
}
413+
414+
const songName = getItemName(new Song("wonderful wonderful", 300000));
415+
console.log("Song Name :", songName);
416+
417+
const playlistName = getItemName(
418+
new Playlist("The Best Songs", [new Song("The Man", 30000)])
419+
);
420+
421+
console.log("Playlist Name :", playlistName);
422+
```

typescript-masterclass/src/app.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,21 @@ console.log(bar);
1010
// console.log(Object.getPrototypeOf(bar) === Foo.prototype);
1111

1212
class Song {
13+
kind: "song";
1314
constructor(public title: string, public duration: number) {}
1415
}
1516

1617
class Playlist {
18+
kind: "playlist";
1719
constructor(public name: string, public songs: Song[]) {}
1820
}
1921

2022
function isSong(item: any): item is Song {
21-
return item instanceof Song;
23+
return "title" in item;
2224
}
2325

2426
function getItemName(item: Song | Playlist) {
25-
if (isSong(item)) {
27+
if (item.kind === "song") {
2628
return item.title;
2729
}
2830
return item.name;

0 commit comments

Comments
 (0)