Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lesson 16 is not working properly #2

Open
eran-nussbaum opened this issue Jun 21, 2020 · 1 comment
Open

Lesson 16 is not working properly #2

eran-nussbaum opened this issue Jun 21, 2020 · 1 comment

Comments

@eran-nussbaum
Copy link

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.

@StefanCardnell
Copy link

StefanCardnell commented May 26, 2021

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) {}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants