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?
JavaScript
x
37
37
1
type ClassConstructor<T> = new(args: any[]) => T
2
3
function withDebug<C extends ClassConstructor<{
4
getDebugValue(): object
5
}>>(Class: C) {
6
return class extends Class {
7
constructor(args: any[]) {
8
super(args)
9
}
10
11
debug() {
12
let Name = Class.constructor.name
13
let value = this.getDebugValue()
14
return `${Name} (${JSON.stringify(value)})`
15
}
16
}
17
}
18
19
class DebugUser {
20
constructor(
21
private id: number,
22
private firstName: string,
23
private lastName: string
24
) {}
25
26
getDebugValue() {
27
return {
28
id: this.id,
29
name: `${this.firstName} ${this.lastName}`
30
}
31
}
32
}
33
34
let User = withDebug(DebugUser)
35
let user = new User(3, 'Lorenzo', "Delaurentis")
36
console.log(user.debug())
37
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
.