TypeScript - *runtime* check if an object implements an interface

problem:

TypeScript - how to perform *runtime* check, if an object implements an interface

In JavaScript there is no such thing as an interface,
so it can be tricky to perform a *runtime* check to see if object A implements interface I.

for example, the instanceof operator will not work against an interface type.


export interface MyInterface {
    getName(): string | null;
}

CLIENT CODE (broken):

if (object instanceof MyInterface) {
  // MyInterface is an interface, not a class
  // so this code will not work at run-time
  // (and should not compile!)
}

solution:
one approach is to use a helper method.
The helper method checks for the existence of a distinctive method of the interface,
and then uses the is keyword in the return type, to return the expected interface type.

export function isMyInterface (object): object is MyInterface {
    const myInterface = object as MyInterface;
    return myInterface.getName !== undefined;
}


CLIENT CODE (OK):

if (isMyInterface(object)) {
  // this code can safely use object as MyInterface ...
}

Comments

  1. Another possible way would be checking against a schema which can be generated with `typescript-json-schema`.

    ReplyDelete

Post a Comment