Reputation: 6844
I have a class that I want to extend with a factory class that will return the correct class based on the input.
class Base<S> {
prop: S;
base() { }
}
class A<S> extends Base<S> {
a() { }
}
class B<S> extends Base<S> {
b() { }
}
interface TypeA {
propA: any;
}
interface TypeB {}
function isTypeA(params: TypeA | TypeB): params is TypeA {
return (params as TypeA).propA !== undefined;
}
function factory(params: TypeA): typeof A;
function factory(params: TypeB): typeof B;
function factory(params: TypeA | TypeB): typeof A | typeof B {
if (isTypeA(params)) {
return A;
} else {
return B;
}
}
const param: TypeA = { propA: {} };
const param2: TypeB = {};
class Test extends factory(param) { }
In addition to that, I need to pass a generics all the way up. How can I pass the generic from the factory function to the Base
class?
Upvotes: 2
Views: 545
Reputation: 18292
Do this:
class Test<T> extends factory(param)<T> { }
Or, if you don't want Test
to be generic:
class Test extends factory(param)<string>()
Upvotes: 2