1
我正在嘗試編寫能夠修改它應用於的類的TypeScript裝飾器。多次實驗後,我來the conclusion it is not yet possible,讓我去使用純函數的不同的路線:使用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)'.
基本上,我試圖去的路線聲明合併通過&
,但目前還沒有解決。
有什麼辦法像這樣改變一個類嗎?