Is there any way, how can I detect whether some object implements some interface?
if(myObj implements IMyInterface) {
//... do something
}
Is there any way, how can I detect whether some object implements some interface?
if(myObj implements IMyInterface) {
//... do something
}
No.
Currently, types are used only during development and compile time. The type information is not translated in any way to the compiled JavaScript code.
With some code generation by the compiler this would be possible. For now the TypeScript team is trying to add as little code as possible to the final JavaScript, the exception being the 'extends' keyword which adds a new method to the compiled output.
Yes, if you use the reflec-ts compiler instead of the standard tsc
compiler. This enhanced version of the TypeScript compiler that allows you to know which interface implements each class of your application. This version of the compiler stores all types information until runtime, and links these information to actual constructors. For example, you can write something like the following:
function implementsInterface(object: Object, target: Interface) {
const objClass: Class = object.constructor && object.constructor.getClass();
if (objClass && objClass.implements) {
let found = false;
for (let base of objClass.implements) {
let found = interfaceExtends(base, target);
if (found) {
return true;
}
}
}
return false;
}
// recursive interface inheritance check
function interfaceExtends(i: Interface, target: Interface) {
if (i === target) {
return true;
}
if (i.extends) {
let found = false;
for (let base of i.extends) {
// do a recursive check on base interface...
found = interfaceExtends(base, target);
if (found) {
return true;
}
}
}
return false;
}
You can find a full working example that suits your needs here
There are a few options for this:
Use a library like ts-interface-checker that generates validation code from your type declarations at build time. More libraries along these lines are listed at Check if an object implements an interface at runtime with TypeScript
Use a compiler extension like reflec-ts -- see @pcan's answer
Write a "type guard" function manually, see https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards