【问题标题】:Possible to extend types in Typescript?可以在 Typescript 中扩展类型吗?
【发布时间】:2017-05-14 02:16:49
【问题描述】:

假设我有以下类型:

type Event = {
   name: string;
   dateCreated: string;
   type: string;
}

我现在想扩展这种类型,即

type UserEvent extends Event = {
   UserId: string; 
}

这不起作用。我该怎么做?

【问题讨论】:

  • type 关键字用于定义type aliases,而不是接口或类。

标签: javascript typescript


【解决方案1】:

你想要达到的效果相当于

interface Event {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

您定义类型的方式不允许指定继承,但是您可以使用交集类型实现类似的效果,正如artem 指出的那样。

【讨论】:

  • 是的,但我不喜欢 interface 这个词,其实我的意思是 type
  • 很公平,那么 artem 的答案应该适合你 :)
【解决方案2】:

关键字extends只能用于接口和类。

如果你只想声明一个有附加属性的类型,你可以使用intersection type

type UserEvent = Event & {UserId: string}

更新用于 TypeScript 2.2,it's now possible to have an interface that extends object-like type,如果类型满足某些限制:

type Event = {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

反之则不行——UserEvent必须声明为接口,而不是type,如果你想使用extends语法。

而且仍然无法使用extend with arbitrary types - 例如,如果Event 是没有任何约束的类型参数,它就不起作用。

【讨论】:

  • 我正在使用 TS v3.5.2,我无法让接口扩展类型。 interface A<T> extends B<T> {blar} 接口只能扩展对象类型或对象类型与静态已知成员的交集
  • @WORMSS 这样做interface Identifiable<T> extends T { id: string } 给我错误“接口只能扩展对象类型或对象类型与静态已知 members.ts(2312) 的交集”
  • 由于 typeScript 是结构类型的,而不是名义上的,扩展没有进一步结构(约束)的“任意类型”可能总是不可能的。
【解决方案3】:

你可以相交类型:

type TypeA = {
    nameA: string;
};
type TypeB = {
    nameB: string;
};
export type TypeC = TypeA & TypeB;

你现在可以在代码中的某个地方做:

const some: TypeC = {
    nameB: 'B',
    nameA: 'A',
};

【讨论】:

  • 这是一个很好的解决方案。我在 React Native 中工作,这让我可以轻松地为我自己的自定义文本输入组件扩展 TextInputProps。谢谢!
  • 太棒了,这就是工作。感谢您的解决方案。
【解决方案4】:

你也可以这样做:

export type UserEvent = Event & { UserId: string; };

【讨论】:

  • 这个答案提供了什么 the 2016 answer 中没有的内容(最后一次编辑于 2019 年,所以没有理由重复它)?
猜你喜欢
  • 2022-12-03
  • 2016-08-16
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多