我找到了无数的线程,其中没有一个线程似乎与我的用例和版本的TypeScript(2.8.1)相匹配。我已经尝试了一些非常基本的类装饰工厂的化身而没有运气。
type Constructable<T> = { new (): T }
function decoratorFactory<T> (): (Base: Constructable<T>) => Constructable<T> {
return function decorator (Base: Constructable<T>): Constructable<T> {
return class extends Base { // line 5
constructor () {
super()
console.log('in constructor')
}
}
}
}
@decoratorFactory()
class Example {}
index.ts(5,5): error TS2322: Type 'typeof (Anonymous class)' is not assignable to type 'Constructable<T>'.
Type '(Anonymous class)' is not assignable to type 'T'.
index.ts(5,26): error TS2509: Base constructor return type 'T' is not a class or interface type.
可以使用类型注释删除第一个错误,但我不明白为什么需要它,并且它对第二个错误没有任何作用。
type Constructable<T> = { new (): T }
function decoratorFactory<T> (): (Base: Constructable<T>) => Constructable<T> {
return function decorator (Base: Constructable<T>): Constructable<T> {
return class extends Base {
constructor () {
super()
console.log('in constructor')
}
} as Constructable<T>
}
}
@decoratorFactory()
class Example {}
index.ts(5,26): error TS2509: Base constructor return type 'T' is not a class or interface type.
我见过一些使用T extends <some empty interface>
的例子,但这对我没有任何帮助:
interface ClassOrInterface {}
type Constructable<T> = { new (): T }
function decoratorFactory<T extends ClassOrInterface> (): (Base: Constructable<T>) => Constructable<T> {
return function decorator (Base: Constructable<T>): Constructable<T> {
return class extends Base {
constructor () {
super()
console.log('in constructor')
}
} as Constructable<T>
}
}
@decoratorFactory()
class Example {}
index.ts(6,26): error TS2509: Base constructor return type 'T' is not a class or interface type.
我看到的答案表明你可以return a constructor function instead of a class。我看到过可以互换使用new () => T
和{ new (): T }
的答案。我见过issues that use cast syntax that is now prohibited。我见过只有return the constructor that was passed in的答案,而不是新的构造函数/类。
我怎样才能做我想做的事?