Use a user-defined type guard to check if an object implements an interface in TypeScript. The user-defined type guard consists of a function, which checks if the passed in object contains specific properties and returns a type predicate.
With the aim to make the code robust, i would like to check that the class implements the interface before instantiation / casting. I would like the the keyword 'instanceof' to verify a class implements an interface, as i understand it, it only verifies class type.
If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface. By casting object1 to a Relatable type, it can invoke the isLargerThan method.
For an instance
Character.Gorgon gor = new Character.Gorgon();
Then do
gor instanceof Monster
For a Class instance do
Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);
Use
if (gor instanceof Monster) {
//...
}
In general for AnInterface
and anInstance
of any class:
AnInterface.class.isAssignableFrom(anInstance.getClass());
If you want a method like public void doSomething([Object implements Serializable])
you can just type it like this public void doSomething(Serializable serializableObject)
. You can now pass it any object that implements Serializable but using the serializableObject
you only have access to the methods implemented in the object from the Serializable interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With