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?
If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class) Class#isAssignableFrom(Class) also returns true if both classes are same. To find if an object is instance of a class use instanceof operator.
TypeScript type check is used to validate the type of any variable at runtime. Type checking has proven to be a good feature for most JavaScript developers. We will start with the most basic library provided by TypeScript, which will directly validate the type of single variables in the code.
Use the instanceof operator to check if an object is an instance of a class, e.g. if (myObj instanceof MyClass) {} . The instanceof operator checks if the prototype property of the constructor appears in the prototype chain of the object and returns true if it does.
TypeScript defines a constructor using the constructor keyword. A constructor is a function and hence can be parameterized. The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class's field are the same.
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
(code in playground)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With