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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-10-06 11:00:00 +0000
Seen: 12 times
Last updated: Jun 28 '21
Can the admin UI interface created using electron.js draw over an existing app in Windows?
How do you call a method in a custom view from a ViewModel?
What is the proper way to utilize the type map[string]interface {} in Golang?
Why isn't the user interface updating when adding a custom object with data binding in .NET MAUI?
What is the way to execute code once Spring Boot has started?
How can the network interface name be changed using the command line?