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 pilation error saying Operator '===' cannot be applied to types 'string' and '() => any'
.
Is there a way I can check for method existence in TypeScript?
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 pilation error saying Operator '===' cannot be applied to types 'string' and '() => any'
.
Is there a way I can check for method existence in TypeScript?
Share Improve this question edited Dec 13, 2020 at 18:15 PG1 asked Nov 15, 2017 at 7:42 PG1PG1 1,2422 gold badges12 silver badges28 bronze badges 3- 1 Just ment out the function call as long as the function isn't implemented yet. – Cerbrus Commented Nov 15, 2017 at 7:45
- @Cerbrus Actually I want to check-in my code which should work before/ after implementation of the non-existent function. – PG1 Commented Nov 15, 2017 at 7:50
- 3 @Cerbrus Why is this closed as dublicate? This question is about TypeScrtipt and that one is about JS. TypeScript does add quite a bit of difficulty. If you try to check if non-existant function exists then the tools will yell that "such field doens't exist, don't do it" which exactly what you check. However when you override a method that may or may not be implemented it makes sence to check if its ancesor exists. – Gherman Commented Mar 4, 2020 at 12:26
1 Answer
Reset to default 17You can use typeof
operator to get the type 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();
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743276753a4462278.html
评论列表(0条)