如何在Typescript中将类型转换为接口
如何在Typescript中将类型转换为接口
在TypeScript中,有没有一种方法可以将 type
转换为 interface
?
我已经阅读了StackOverflow上的这个QA,但我认为它与我在这个问题中描述的不太匹配。
以下是一个快速示例,其中 Product
被定义为来自第三方TypeScript库的 type
。
// ProductFragmentOne用于突出显示组合(联合等)的可能性 type Product = ProductFragmentOne&{sku:string};
要将该 Product
集成到我们自己的系统中,已经可以通过扩展(联合) type
来实现,如下面的示例所示:
export type ProductSchema = Product&{ name:string; }
我的问题是:
- 我们的
ProductSchema
是否可以被定义为interface
?这有可能吗?
#代码可能的外观示例 export interface ProductSchema{ name:string; //在此处添加Product属性的魔法 }
更新:采用这种方法的原因纯粹是对 interface
优于 type
的偏好。它使现有代码保持其风格,而不考虑采用的第三方库。
谢谢。
在TypeScript中,有时我们需要将一个类型(type)转换为接口(interface)。这个问题的解决方法是使用TypeScript 2.2中引入的新特性:接口可以继承类型。
具体来说,我们可以使用extends关键字或运算符来让一个接口继承一个类型。例如,我们可以这样定义一个接口ProductSchema,它继承了一个类型Product:
export interface ProductSchema extends Product{ name: string; } type Product = { SKU: string }
这样,ProductSchema接口就包含了Product类型的属性,并且添加了一个名为name的属性。
在解决这个问题时,我找到了一个与此问题无关的答案,即"Is it Possible to extend types in Typescript?"。这个答案提到了TypeScript 2.2中接口可以继承类型的特性。
另外,我们可以在StackOverflow上找到关于接口和类型之间区别的详细讨论,《TypeScript: Interfaces vs Types》。
除了上述的方法,还有一个额外的例子可以参考,可以在TypeScript playground上查看。
有没有一种方法可以不声明一个单独的类型定义,让接口直接继承一个类型定义呢?例如可以这样写:`export interface ProductSchema extends typeof ProductObj{ name: string; }`。
需要注意的是,"An interface can only extend an object type or intersection of object types with statically known members.ts(2312)",所以以下的写法不起作用:`const ctype: Readonly