admin管理员组文章数量:1337159
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();
}
本文标签: javascriptCheck if method exists in a class in TypeScriptStack Overflow
版权声明:本文标题:javascript - Check if method exists in a class in TypeScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743276753a2493507.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论