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:
ProductSchema
to be defined as an interface
? 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 a preference for interface
over type
. It makes 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
andtype
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