【发布时间】:2021-01-10 14:28:51
【问题描述】:
我正在处理这个创建 mixin 的 TypeScript 代码:
function applyMixins(derivedCtor: Function, constructors: Function[]) {
//Copies methods
constructors.forEach((baseCtor) => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
Object.defineProperty(
derivedCtor.prototype,
name,
Object.getOwnPropertyDescriptor(baseCtor.prototype, name) ||
Object.create(null)
);
});
});
//Copies properties
constructors.forEach((baseCtor) => {
let empty = new baseCtor();
Object.keys(empty).forEach((name) => {
Object.defineProperty(
derivedCtor.prototype,
name,
Object.getOwnPropertyDescriptor(empty, name) ||
Object.create(null)
);
});
});
}
它没有编译,抱怨这一行:let empty = new baseCtor();:TS2351: This expression is not constructable. Type 'Function' has no construct signatures.。我知道这可以通过将第一行中的两个Function 类型引用与any 交换来解决,但我试图在没有any 的情况下过我的生活,因为告诉TypeScript 关闭它通常是一种草率的方式起来。
有没有办法在不使用any的情况下实现这段代码?
【问题讨论】:
-
Function是不可构造的,而new () => object或{new(): object}是可构造的。 this 是否适用于您的用例?如果是这样,我会在有机会时写一个答案。如果不是,请在问题文本中用相关示例进行详细说明。祝你好运! -
谢谢,我在模块里加了
declare type ctorType = new() => object;,然后用ctorType代替Function。但是和{new(): object}相比有什么区别呢?
标签: typescript mixins