Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type checking class (not instance of class) extends another class

Tags:

typescript

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?

like image 911
Kyle Fahringer Avatar asked Mar 12 '17 22:03

Kyle Fahringer


People also ask

How do you check if a class extends another class in Java?

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.

What is type checking in TypeScript?

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.

How do I check my TypeScript Instanceof?

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.

What is instance in TypeScript?

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.


1 Answers

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)

like image 167
Nitzan Tomer Avatar answered Sep 29 '22 11:09

Nitzan Tomer