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

时间:2016-09-28 16:19:05

标签: typescript

我试图编写一个能够修改它所应用的类的TypeScript装饰器。经过多次实验,我来到了the conclusion it is not yet possible,所以我选择了一个使用普通函数的不同路径:

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)'.

我基本上试图通过&进行声明合并的路线,但到目前为止还没有结束。

有没有办法改变像这样的类?

1 个答案:

答案 0 :(得分:0)

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