【问题标题】:How to convert type to interface in Typescript如何在 Typescript 中将类型转换为接口
【发布时间】:2021-01-17 17:56:59
【问题描述】:

从一个类型化的 Object 中,是否可以将其转换为 TypeScript 中的接口?

我已经阅读了this QA here on StackOverflow,并且认为它与我在此问题中给出的描述不太吻合。

快速示例,在这种情况下,type Product 被定义为来自第三方 TypeScript 库的type

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

要将该产品集成到我们自己的系统中,已经可以通过扩展(联合)一个类型,如下例所示:

export type ProductSchema = Product & { 
  name: string;
}

我的问题是:

  • 有没有办法将我们的ProductSchema 定义为interface,而不是使用类型方法?还是有可能?
# Example of how the code may look
export interface ProductSchema{ 
  name: string;
  // do the magic to add Product properties here
}

更新:这种方法的原因纯粹是接口优先于类型。也使现有代码保持其风格,无论采用何种第三方库。

谢谢。

【问题讨论】:

  • 不,可能不是。如果 type 已经是其键是静态已知的对象类型(或对象类型的交集),则只能从 type 创建一个 interface。由于Product 是一个联合,它不满足限制。当然{ ... } 不是实际代码,所以这不是minimal reproducible example,我可以肯定以某种方式。你为什么要interface?您出于某种原因需要吗?还是只是偏好?
  • 没有任何理由这样做,因为几乎所有你可以用接口做的事情也可以用类型来做。如果 Product 是联合类型,那么可能是有原因的,即使您可以定义两种类型的 Product 对象都扩展的基本接口,也可能会出现您可以创建可分配给基本接口的对象的情况但不能分配给产品,因为它基于两种产品类型的冲突部分。你不想要那个。你不想这样做。
  • 我更新了这个问题,对前两个 cmets 进行了更多说明。人们编写代码的方式确实不同,一个项目中使用的风格不应影响依赖项目的编写方式(结构化)。

标签: typescript types interface


【解决方案1】:

为了解决这个问题,我使用了在一个完全不相关的问题上找到的答案:Is it "Possible to extend types in Typescript?"

事实上,从 TypeScript 2.2 开始——interface 可以扩展 type

在这个 StackOverflow 线程上,interfacetype 之间的区别有一个广泛的线程:TypeScript: Interfaces vs Types

export interface ProductSchema extends Product{ 
  name: string;
}
# Where the Product is a type similar to
type Product = { SKU: string }

我一直在寻找的“魔术”确实是extends 运算符(或关键字)。 TypeScript playground based on this same approach 上还有一个附加示例

【讨论】:

  • 任何人都有一个技巧,那就是不必声明单独的类型定义,这样我们就可以做到export interface ProductSchema extends typeof ProductObj{ name: string; }
猜你喜欢
  • 2018-08-28
  • 2018-11-28
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
相关资源
最近更新 更多