File tree Expand file tree Collapse file tree 2 files changed +48
-1
lines changed
Expand file tree Collapse file tree 2 files changed +48
-1
lines changed Original file line number Diff line number Diff line change @@ -332,3 +332,46 @@ const playlistName = getItemName(
332332
333333console .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+ ```
Original file line number Diff line number Diff 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+
2024function getItemName ( item : Song | Playlist ) {
21- if ( item instanceof Song ) {
25+ if ( isSong ( item ) ) {
2226 return item . title ;
2327 }
2428 return item . name ;
You can’t perform that action at this time.
0 commit comments