Reputation: 294
Given the class below:
class BaseClass {}
I want to create another class which extends this class, i.e.:
class ExtendedClass extends BaseClass {}
I then want to pass the ExtendedClass
as an argument to another function (not an instance of an ExtendedClass
, but the class itself!), and type check this by ensuring the ExtendedClass
extends BaseClass
.
This doesn't work:
function helloClass (c: BaseClass) {}
because c: BaseClass
denotes that c
should be an instance of a BaseClass
(or something which extends a BaseClass
) - but not a class which extends BaseClass
itself.
Is this at all possible within TypeScript?
Upvotes: 9
Views: 4078
Reputation: 164367
You can represent classes like this: { new(): BaseClass }
.
Or in an example:
interface BaseClassConstructor<T extends BaseClass> {
new (): T;
}
class BaseClass {
str: string;
}
class ExtendedClass extends BaseClass { }
function fn<T extends BaseClass>(ctor: BaseClassConstructor<T>) {
}
fn(BaseClass); // fine
fn(ExtendedClass); // fine
class A {
prop: any;
}
fn(A); // error
Upvotes: 11