P.M
P.M

Reputation: 3168

How to convert type to interface in Typescript

Is there a way in TypeScript to transform a type into an interface?

I already read this QA here on StackOverflow, and don't think it fits well with the description I give in this Question.

A quick example of a scenario where a Product is defined as type from a third-party TypeScript library.

// ProductFragmentOne is used to highlight the possibility of composition(unions, etc)
type Product = ProductFragmentOne & { sku: string };

To integrate that Product into our own system, it is already possible by extending(union) a type as in the following example:

export type ProductSchema = Product & { 
  name: string;
}

My question is:

# Example of how the code may look
export interface ProductSchema{ 
  name: string;
  //Do the magic to add Product properties here
}

Update: The reason for this approach is purely a preference for interface over type. It makes existing code keep its style, regardless of third party library adopted.

Thanks.

Upvotes: 12

Views: 26355

Answers (1)

P.M
P.M

Reputation: 3168

To solve this problem, I used an answer found on a completely unrelated question: Is it "Possible to extend types in Typescript?".

In fact, since TypeScript 2.2 -- It is possible for an interface to extend a type.

There is an extensive thread on the difference between interface and type on this StackOverflow thread: TypeScript: Interfaces vs Types

export interface ProductSchema extends Product{ 
  name: string;
}

// Where the Product is a type similar to
type Product = { SKU: string }

The "magic trick" I was looking for was indeed that extends operator(or keyword). There is an additional example on TypeScript playground based on this same approach as well

Upvotes: 20

Related Questions