【发布时间】:2022-01-23 22:22:14
【问题描述】:
我在一家工厂工作;我最终需要添加自定义方法,感谢this answer 和this answer,我们能够使其几乎按预期工作。
几乎是因为它只适用于没有任何必需参数的方法;如果我们尝试添加具有至少一个必需参数的方法,则会出现编译错误。
我尝试在 method 参数和 M 类型的声明中添加一个 rest 参数数组(见下文),但它仅在调用方法时有帮助。
(this: E & S, ...args: unknonwn[]) => unknown
type Base = { id: string }
type Factory<E> = new () => E;
function factory<E extends Base>(name: string): Factory<E>;
function factory<E extends Base, M extends Record<string, <S extends M>(this: E & S, ...args: unknown[]) => unknown>>(
name: string, methods: M & Record<string, ((this: E & M, ...args: unknown[]) => void)>
): Factory<E & M>;
function factory<E extends Base, M extends Record<string, <S extends M>(this: E & S) => unknown>>(
name: string, methods?: M
): Factory<E> {
const ret = function (this: Base) {
this.id = "0"
};
Object.defineProperty(ret, "name", { value: name });
if (methods) for (const method in methods) Object.defineProperty(ret.prototype, method, { value: methods[method] });
return ret as unknown as Factory<E>;
}
const T1 = factory("T1");
const t1 = new T1();
console.log(t1, t1.id);
const T2 = factory(
"T2",
{
foo: function (repeat: boolean) {
const ret = ! repeat;
if(repeat) this.foo(ret);
return ret;
}
},
);
const t2 = new T2();
console.log(t2, t2.id, t2.foo(true));
这是一个playground 进行实验。
【问题讨论】:
-
将
unknown[]替换为any[]。见example。别担心,any提供不安全行为时并非如此。这意味着您的函数可以返回任何参数并期望任何参数。让我知道它是否有帮助 -
不仅仅是“它有帮助”,我会说“它解决了”!返回类型也可以是
void(至少在我到目前为止所做的测试中)。如果您介意更改答案中的评论,我可以接受
标签: typescript typescript-generics