Krishna Acharya
Krishna Acharya

Reputation: 503

Define the return type of a function based on argument

I want to define a method in class that will have type based on argument supplied on constructor such as:

class A {
    private model: any;
    constructor(model: any) {
        this.model = model;
    }

    getModel() {
        return this.model;
    }
}

class B {
    hello() {
        console.log("hi");
    }
}

class C {
    hi() {
        console.log("hi");
    }
}

const objA = new A(new B());

const objb = objA.getModel();

objb.hello();

Here the type of objb is any, which is the type of model in class A, but I want it to be the type of class B or any class object I pass into the A class constructor. How can I achieve this in TypeScript?

Upvotes: 0

Views: 92

Answers (1)

BorisTB
BorisTB

Reputation: 1806

Use Typescript generics

class A<Model> {
    private model: Model;
    constructor(model: Model) {
        this.model = model;
    }

    getModel(): Model {
        return this.model;
    }
}

class B {
    hello() {
        console.log("hi");
    }
}

class C {
    hi() {
        console.log("hi");
    }
}

const objA = new A(new B());

const objb = objA.getModel();

objb.hello();

Playground

Upvotes: 1

Related Questions