typescript class 装饰器:覆盖构造函数但保留 class 名称?
typescript class decorator: override the constructor but preserve the class name?
typescript 手册有一个示例,说明如何使用 class 装饰器来覆盖构造函数 (link):
function classDecorator<T extends { new (...args: any[]): {} }>(
constructor: T
) {
return class extends constructor {
newProperty = "new property";
hello = "override";
};
}
@classDecorator
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
当我注销生成的 class 的实例时,class 名称丢失:
console.log(new Greeter("world"));
//=> { "property": "property", "hello": "override", "newProperty": "new property" }
现在,如果我修改装饰器以将新的 class 分配给变量,则日志将包含该变量的名称:
function classDecorator2<T extends { new (...args: any[]): {} }>(
constructor: T
) {
const MyDecoratedClass = class extends constructor {
newProperty = "new property";
hello = "override";
};
return MyDecoratedClass
}
@classDecorator2
class Greeter2 {
// ... same as Greeter
}
console.log(new Greeter2("world"));
//=> MyDecoratedClass: { "property": "property", "hello": "override", "newProperty": "new property" }
有没有办法在控制台输出中保留 class 的原始名称?例如。我希望最后一个控制台语句的输出是
Greeter2: { "property": "property", "hello": "override", "newProperty": "new property" }
typescript 沙箱中可用的所有代码示例here
你可以试试这样的东西,虽然看起来有点老套。
function classDecorator<T extends { new (...args: any[]): {} }>(
constructor: T
) {
const cls = class extends constructor {
newProperty = "new property";
hello = "override";
};
Object.defineProperty(cls, 'name', {
get: () => `${constructor.name}Generated`
});
return cls
}
typescript 手册有一个示例,说明如何使用 class 装饰器来覆盖构造函数 (link):
function classDecorator<T extends { new (...args: any[]): {} }>(
constructor: T
) {
return class extends constructor {
newProperty = "new property";
hello = "override";
};
}
@classDecorator
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
当我注销生成的 class 的实例时,class 名称丢失:
console.log(new Greeter("world"));
//=> { "property": "property", "hello": "override", "newProperty": "new property" }
现在,如果我修改装饰器以将新的 class 分配给变量,则日志将包含该变量的名称:
function classDecorator2<T extends { new (...args: any[]): {} }>(
constructor: T
) {
const MyDecoratedClass = class extends constructor {
newProperty = "new property";
hello = "override";
};
return MyDecoratedClass
}
@classDecorator2
class Greeter2 {
// ... same as Greeter
}
console.log(new Greeter2("world"));
//=> MyDecoratedClass: { "property": "property", "hello": "override", "newProperty": "new property" }
有没有办法在控制台输出中保留 class 的原始名称?例如。我希望最后一个控制台语句的输出是
Greeter2: { "property": "property", "hello": "override", "newProperty": "new property" }
typescript 沙箱中可用的所有代码示例here
你可以试试这样的东西,虽然看起来有点老套。
function classDecorator<T extends { new (...args: any[]): {} }>(
constructor: T
) {
const cls = class extends constructor {
newProperty = "new property";
hello = "override";
};
Object.defineProperty(cls, 'name', {
get: () => `${constructor.name}Generated`
});
return cls
}