typescript-masterclass-src icon indicating copy to clipboard operation
typescript-masterclass-src copied to clipboard

Lesson 16 is not working properly

Open eran-nussbaum opened this issue 5 years ago • 1 comments

Hello,

In "16-in-operator-literal-type-guard" folder I run tsc and then node app/dist.js and the output is:

Song name: undefined
Playlist name: The Best Songs

However, if I switch the commenting out between lines 16 and 17 from:

  // if (isSong(item)) {
  if (item.kind === 'song') {

to

  if (isSong(item)) {
  // if (item.kind === 'song') {

then the output is properly:

Song name: Wonderful Wonderful
Playlist name: The Best Songs

It seems like something with the kind approach is not working properly.

eran-nussbaum avatar Jun 21 '20 09:06 eran-nussbaum

Ditto, was confused in the lesson how simply kind: 'song' on the class definition could later be used to test in the if condition. Alas, it can't be used, as seen in the compiled JS code:

var Song = /** @class */ (function () {
    function Song(title, duration) {
        this.title = title;
        this.duration = duration;
    }
    return Song;
}());
var Playlist = /** @class */ (function () {
    function Playlist(name, songs) {
        this.name = name;
        this.songs = songs;
    }
    return Playlist;
}());
function isSong(item) {
    return 'title' in item;
}
function getItemName(item) {
    // if (isSong(item)) {
    if (item.kind === 'song') {
        return item.title;
    }
    return item.name;
}
var songName = getItemName(new Song('Wonderful Wonderful', 300000));
console.log('Song name:', songName);
var playlistName = getItemName(new Playlist('The Best Songs', [new Song('The Man', 300000)]));
console.log('Playlist name:', playlistName);

Tried TypeScript 4.2.4 and 2.7.2 (lesson version).

kind is forced to have a type of 'song' but it has to be assigned somewhere in the TypeScript which the example missing. Since const isn't allowed in class definitions the next best thing is readonly:

class Song {
  readonly kind = 'song';
  constructor(public title: string, public duration: number) {}
}

StefanCardnell avatar May 26 '21 11:05 StefanCardnell