打字稿类装饰器:重写构造函数,但保留类名称? [英] typescript class decorator: override the constructor but preserve the class name?

查看:65
本文介绍了打字稿类装饰器:重写构造函数,但保留类名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打字稿手册中有一个示例,说明了如何使用类修饰符覆盖构造函数(

The typescript handbook has an example of how to use a class decorator to override the constructor (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;
  }
}

当我注销结果类的实例时,类名丢失:

When I log out an instance of the resulting class, the class name is missing:

console.log(new Greeter("world"));
//=> { "property": "property", "hello": "override", "newProperty": "new property" }

现在,如果我修改装饰器以将新类分配给变量,则日志将包含该变量的名称:

Now, if I modify the decorator to assign the the new class to a variable, the log will contain the name of that variable:

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" } 

有没有一种方法可以在控制台输出中保留类的原始名称?例如.我希望最后一个控制台语句的输出为

Is there a way I can preserve the original name of the class in the console output? E.g. I would like the output of that last console statement to be

Greeter2: { "property": "property", "hello": "override", "newProperty": "new property" }

在打字稿沙箱这里

推荐答案

您可以尝试类似的方法,但是似乎有点怪癖.

You could try something like this, seems a bit hacky though.

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
}

这篇关于打字稿类装饰器:重写构造函数,但保留类名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆