File tree Expand file tree Collapse file tree 2 files changed +49
-2
lines changed
Expand file tree Collapse file tree 2 files changed +49
-2
lines changed Original file line number Diff line number Diff line change @@ -375,3 +375,48 @@ const playlistName = getItemName(
375375
376376console .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+ ```
Original file line number Diff line number Diff line change @@ -10,19 +10,21 @@ console.log(bar);
1010// console.log(Object.getPrototypeOf(bar) === Foo.prototype);
1111
1212class Song {
13+ kind : "song" ;
1314 constructor ( public title : string , public duration : number ) { }
1415}
1516
1617class Playlist {
18+ kind : "playlist" ;
1719 constructor ( public name : string , public songs : Song [ ] ) { }
1820}
1921
2022function isSong ( item : any ) : item is Song {
21- return item instanceof Song ;
23+ return "title" in item ;
2224}
2325
2426function getItemName ( item : Song | Playlist ) {
25- if ( isSong ( item ) ) {
27+ if ( item . kind === "song" ) {
2628 return item . title ;
2729 }
2830 return item . name ;
You can’t perform that action at this time.
0 commit comments