简体   繁体   中英

How to convert type to interface in Typescript

From a typed Object, is it possible to transform it into an interface in TypeScript?

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

Quick Example, this scenario where type Product is defined as type from a third-party TypeScript library.

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

To integrate that product in 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:

  • Is there a way for our ProductSchema to be defined as an interface , instead of using the types approach? Or is that even possible?
# 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 preference of interfaces over types. Also to make existing code keep its style, regardless of third party library adopted.

Thanks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM