Im trying to learn and understand Typescript Generics but I'm stuck with the following situation:
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})
Im getting this from 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'.
CodePudding user response:
You just need a minor tweak to your function:
function testing<T extends typeof A>(config?: IConfig<T | typeof A>) {
const conf = config ?? { class: A }
const thisClass = new conf.class();
thisClass.helloworld();
}
You can't in general have a default assignment with a generic like that, unless you explicitly include the default type along with the generic like I've included with IConfig<T | typeof A>
otherwise the compiler will correctly complain that you haven't covered all the possible T's. Note this holds true even if your T extends your default type: T could still be a more complex superset of A.