File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -264,3 +264,32 @@ const item: Record<keyof TrackStates, string> = {
264264// Number are coerced to string
265265dictionary [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+ ```
Original file line number Diff line number Diff line change 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 ) ;
You can’t perform that action at this time.
0 commit comments