假设我有以下类型:
type Event = {
name: string;
dateCreated: string;
type: string;
}
我现在想扩展这种类型,即
type UserEvent extends Event = {
UserId: string;
}
这行不通。我该怎么做?
最佳答案
关键字extends
只能用于接口(interface)和类。
如果你只想声明一个有额外属性的类型,你可以使用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;
}
反之则不行 - 如果您想使用 extends
语法,UserEvent
必须声明为接口(interface),而不是 type
.
而且还是无法使用extend
with arbitrary types - 例如,如果 Event
是一个没有任何约束的类型参数,它就不起作用。
关于javascript - 可以在 Typescript 中扩展类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41385059/