我試圖學習和理解 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})
我從 WebStorm 得到這個Type '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'.
uj5u.com熱心網友回復:
你只需要對你的功能做一個小的調整:
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 的更復雜的超集。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/526635.html
標籤:打字稿班级目的界面
