Skip to content
Advertisement

TypeScript Mixins and Constructor Names

I have this sample of code experimenting with mixins in TypeScript. However, it is not returning what I am expecting.

It should give me: User ({"id":3,"name":"Lorenzo Delaurentis"}).

Instead, I am getting: Function ({"id":3,"name":"Lorenzo Delaurentis"}).

The line let Name = Class.constructor.name should give me User, but it is not. Am I missing something obvious here?

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

function withDebug<C extends ClassConstructor<{
    getDebugValue(): object
}>>(Class: C) {
    return class extends Class {
        constructor(...args: any[]) {
            super(...args)
        }

        debug() {
            let Name = Class.constructor.name
            let value = this.getDebugValue()
            return `${Name} (${JSON.stringify(value)})`
        }
    }
}

class DebugUser {
    constructor(
        private id: number,
        private firstName: string,
        private lastName: string
    ) {}

    getDebugValue() {
        return {
            id: this.id,
            name: `${this.firstName} ${this.lastName}`
        }
    }
}

let User = withDebug(DebugUser)
let user = new User(3, 'Lorenzo', "Delaurentis")
console.log(user.debug())

P.S. I compiled with tsc mixins --target ES6. Otherwise, I get an error: error TS2339: Property 'name' does not exist on type 'Function'.

Advertisement

Answer

You want just Class.name. The Class.constructor is Function.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement