如何在 Typescript 中将类型转换为接口

P.M*_*P.M 9 types interface typescript

TypeScript 有没有办法将 a 转换type为 an interface

我已经在 StackOverflow 上阅读了这个 QA,并且认为它与我在这个问题中给出的描述不太相符。

一个场景的快速示例,其中 aProduct被定义为type来自第三方 TypeScript 库。

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

要将其集成Product到我们自己的系统中,可以通过扩展(联合)a来实现,type如下例所示:

export type ProductSchema = Product & { 
  name: string;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • 有没有办法让 ourProductSchema被定义为 an interface?这可能吗?
# Example of how the code may look
export interface ProductSchema{ 
  name: string;
  //Do the magic to add Product properties here
}
Run Code Online (Sandbox Code Playgroud)

更新:interface这种方法的原因纯粹是对over的偏好type。它使现有代码保持其风格,无论采用何种第三方库。

谢谢。

P.M*_*P.M 16

为了解决这个问题,我使用了在一个完全不相关的问题上找到的答案:“是否可以在 Typescript 中扩展类型?”

事实上,从 TypeScript 2.2 开始, an 就可以interface扩展type.

有一个关于 StackOverflow 线程interface之间的差异的广泛线程: TypeScript: Interfaces vs Typestype

export interface ProductSchema extends Product{ 
  name: string;
}

// Where the Product is a type similar to
type Product = { SKU: string }
Run Code Online (Sandbox Code Playgroud)

我正在寻找的“魔术”确实是那个extends运算符(或关键字)。TypeScript Playground 上还有一个基于相同方法的示例

  • 也许应该指出:“接口只能扩展对象类型或对象类型与静态已知成员的交集。ts(2312)”,因此不幸的是,以下构造不起作用: `const ctype: Readonly<string[ ]> = ["a", "b"] 作为常量;类型 ttype = typeof ctype[数字]; 接口 xyz 扩展 ttype {...}` (2认同)