Suppose I have an interface MyInterface
Is there a native way in typescript to check if an object complies to MyInterface
?
Like instanceof
but against an interface instead of a class.
Suppose I have an interface MyInterface
Is there a native way in typescript to check if an object complies to MyInterface
?
Like instanceof
but against an interface instead of a class.
As far as I know there is no way, because I tried it several times with instanceof
. It works for classes although.
So you have to check for the props of the object e.g.
if((object as SomeInterface).interfaceMethod)){
// it's SomeInterface
} else {
// it's not
}
There is no native way, but ts-interface-checker module can be used for runtime tests and validations.
It needs a runtime description of the interface, which can be built from the TypeScript interfaces in one step using the companion ts-interface-builder module.