Check if method exists in a class in TypeScript

Viewed 16551

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?

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();
}
Related