Lesson 16 is not working properly
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.
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) {}
}