繁体   English   中英

使用TypeScript类装饰器更改类类型

[英]Change class type using a TypeScript class decorator

我正在尝试编写一个TypeScript装饰器,该装饰器能够修改其应用于的类。 经过大量的实验,我得出的结论是尚不可能 ,因此我走了一条使用普通函数的不同路线:

function component<P, T extends { props: P }, C extends { new(): T }>(cls: C) {
  return cls as C & P;
}

const Comp = component(class {
  props = {
    myOptionalString: undefined as string | undefined,
    myNumber: 5 as number,
  };

  static render(elem: typeof Comp) {
    const num: number = elem.myNumber;  // LINE 87
  }
});

const empty: typeof Comp | undefined = undefined;
const c = new Comp();
c.myOptionalString = 'hi';  // LINE 93

但是,这也不起作用:

ERROR in ./src/index.tsx
(87,30): error TS2339: Property 'myNumber' does not exist on type 'typeof (Anonymous class) & {}'.

ERROR in ./src/index.tsx
(93,3): error TS2339: Property 'myOptionalString' does not exist on type '(Anonymous class)'.

我基本上是想通过&进行声明合并的方法,但是到目前为止还没有奏效。

有什么办法可以改变这样的班级吗?

确保其显示const Comp: comp<{etc}> = comp (class, etc.)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM