1 | initial version |
If all available types have identical methods, then you can simply cast the interface to the desired type like this:
interface MyInterface {
doSomething(): void;
}
class MyClass implements MyInterface {
doSomething() {
console.log("Doing something");
}
}
const myInstance: MyInterface = new MyClass();
const myInstanceAsClass = myInstance as MyClass;
In the above example, we have an interface MyInterface
and a class MyClass
that implements it. We create an instance of MyClass
and cast it to MyInterface
. Then, we cast myInstance
back to MyClass
using the as
keyword. Since both MyClass
and MyInterface
have identical methods, this works without any issues.