Ask Your Question
2

How can you convert an interface to a specific type if all available types have identical methods?

asked 2022-10-06 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-06-28 03:00:00 +0000

scrum gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-10-06 11:00:00 +0000

Seen: 12 times

Last updated: Jun 28 '21