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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With