Typescript在接口中存储对泛型类的引用,然后从该类创建对象



我试图学习和理解Typescript泛型,但我遇到了以下情况:

class A {
helloworld() {
console.log('hello world a')
}
}
interface IConfig<T extends typeof A> {
class: T
}
function testing<T extends typeof A>(config?: IConfig<T>) {
if (config === undefined) {
config = {class: A};
}
const thisClass = new config.class();
thisClass.helloworld();
}
testing();
class B extends A {
helloworld() {
console.log('hello world b')
}
}
testing({class: B})

我从WebStormType 'typeof A' is not assignable to type 'T'.   'typeof A' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'typeof A'.得到这个

您只需要对函数进行一个小调整:

function testing<T extends typeof A>(config?: IConfig<T | typeof A>) {
const conf = config ?? { class: A }
const thisClass = new conf.class();
thisClass.helloworld();
}

游乐场

一般来说,你不能用这样的泛型进行默认赋值,除非你显式地将默认类型和我在IConfig<T | typeof A>中包含的泛型一起包含,否则编译器会正确地抱怨你没有涵盖所有可能的t。请注意,即使你的T扩展了你的默认类型,这也是正确的:T仍然可能是a的一个更复杂的超集。

相关内容

最新更新