[英]How to convert type to interface in Typescript
From a typed Object, is it possible to transform it into an interface in TypeScript?从类型化对象,是否可以将其转换为 TypeScript 中的接口?
I already read this QA here on StackOverflow , and don't think it fits well with the description I give in this Question.
我已经在 StackOverflow 上阅读了这个 QA ,并且认为它与我在这个问题中给出的描述不太吻合。
Quick Example, this scenario where type Product
is defined as type
from a third-party TypeScript library.简单的例子,这种场景
type Product
被定义为type
从第三方打字稿库。
# 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:我的问题是:
ProductSchema
to be defined as an interface
, instead of using the types approach?ProductSchema
定义为interface
,而不是使用类型方法? 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?"为了解决这个问题,我使用了一个完全不相关的问题的答案:“是否可以在 Typescript 中扩展类型?” .
.
In fact, since TypeScript 2.2 -- It is possible for an interface
to extend a type
.事实上,从 TypeScript 2.2 开始——
interface
可以扩展type
。
There is an extensive thread on the difference between
interface
andtype
on this StackOverflow thread: TypeScript: Interfaces vs Types在这个 StackOverflow 线程上有一个关于
interface
和type
之间区别的广泛线程: 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).我正在寻找的“魔术”确实是
extends
运算符(或关键字)。 There is an additional example on TypeScript playground based on this same approach as well在TypeScript 操场上还有一个基于相同方法的额外示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.