bcherny/programming-typescript-answers

withEZDebug Mixin not working as expected

luisorbaiceta opened this issue · 0 comments

In chapter Five, Mixins section, the expected behaviour is that withEZDebug mixin logs:
ClassName {"id": 3, "name": "The Name"}
But is logging Function {"id": 3, "name": "The Name"} instead. @bcherny

// MIXINS
type ClassConstructor<T> = new(...args: any[]) => T;

function withEZDebug<C extends ClassConstructor<{ getDebugValue(): object }>>(Class: C) {
    return class extends Class {
        debug() {
            let Name = Class.constructor.name;
            let value = this.getDebugValue();
            return Name + '(' + JSON.stringify(value) + ')';
        }
        constructor(...args: any[]) {
            super(...args);
        }
    }
}

class HardToDebugUser {
    constructor(
        private id: number,
        private firstName: string,
        private lastName: string,
    ) {}
    getDebugValue() {
        return {
            id: this.id,
            name: this.firstName + ' ' + this.lastName
        };
    }
}

let User = withEZDebug(HardToDebugUser);
let user = new User(3, 'First Name', 'Second Name');
console.log(user.debug());