0

I have a typescript question here.

I have many model classes, that are all inherited from BaseModel

class BaseModel {
    public isChecked: boolean;
}

class Animal extends BaseModel {
    public id: number;
}

class Car extends BaseModel {
    public hasHotWheels: boolean;
}

Now I need to write a function that accepts arguments that are classes that inherit from the BaseModel. I can explicitly list all the classes, but I have more than 50 models that inherit from the BaseModel class, so my question is, can I somehow state that I expect the function parameter to inherit from a said class like so

function foo( _input: inherits from BaseModel ) {} 

2 Answers 2

8

Generics can help:

function foo<TModel extends BaseModel>( _input: TModel ) {}

Many of the class keywords can be used when describing generics, with more options on the TS roadmap. The type inference can handle this sort of thing easily and, when it fails, you can call foo<FooModel> explicitly and it will still be type-safe.

Sign up to request clarification or add additional context in comments.

Comments

1

Why don't you just use the Parent class as the type for your function, like this:

class ChildA extends Parent {

}

class ChildB extends Parent {

}

function beAwesomeParent(parent: Parent) {
    parent.isCool = true;
}

var childA = new ChildA();
beAwesomeParent(childA);

Tested on the TS Playground without an error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.