Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if method exists in a class in TypeScript [duplicate]

I am having a class in which a method currently doesn't exists but will be added later. I want to use that method if it exists otherwise not. For eg.

Class A {
    public func(string s) {
        // Currently this method is not present in Class A
    }
}

I want to check that if this method exists, then call it, otherwise do something else. I found a solution which works for JavaScript but doesn't work for TypeScript:

let objectOfA = new A();
if ( objectOfA.func === function) {
    objectOfA.func();
}

But this somehow doesn't works in TypeScript and throws compilation error saying Operator '===' cannot be applied to types 'string' and '() => any'.

Is there a way I can check for method existence in TypeScript?

like image 689
Parag Gangil Avatar asked Nov 15 '17 07:11

Parag Gangil


1 Answers

You can use typeof operator to get the ty the of the operand. Although use bracket notation to get unknown properties(to avoid throwing exception).

let objectOfA = new A();
if ( typeof objectOfA['func'] === 'function') {
    objectOfA.func();
}
like image 182
Pranav C Balan Avatar answered Nov 13 '22 02:11

Pranav C Balan