How to create an object based on an interface file definition in TypeScript?

Sometimes, we want to create an object based on an interface file definition in TypeScript.

In this article, we’ll look at how to create an object based on an interface file definition in TypeScript.

How to create an object based on an interface file definition in TypeScript?

To create an object based on an interface file definition in TypeScript, we can create a class that extends the interface.

For instance, we write

interface IModal {
  content: string;
  form: string;
  //...
  foo: (bar: string) => void;
}

class Modal implements IModal {
  content: string;
  form: string;

  foo(param: string): void {}
}

to create the IModal interface with some fields.

Then we create the Modal class that has the fields listed in IModal.

Then we can use new Modal() to create a new Modal instance.

Conclusion

To create an object based on an interface file definition in TypeScript, we can create a class that extends the interface.