假设我有以下类型:
type Event = { name: string; dateCreated: string; type: string; }我现在想扩展这种类型,即
I now want to extend this type, i.e.
type UserEvent extends Event = { UserId: string; }这不起作用.我该怎么做?
This doesn't work. How can I do this?
推荐答案关键字 extends 只能用于接口和类.
The keyword extends can be used for interfaces and classes only.
如果您只想声明具有附加属性的类型,可以使用 交叉路口类型:
If you just want to declare a type that has additional properties, you can use intersection type:
type UserEvent = Event & {UserId: string}UPDATE 对于 TypeScript 2.2,现在可以有一个界面扩展类对象类型,如果类型满足一些限制:
UPDATE for TypeScript 2.2, it's now possible to have an interface that extends object-like type, if the type satisfies some restrictions:
type Event = { name: string; dateCreated: string; type: string; } interface UserEvent extends Event { UserId: string; }反过来不行 - UserEvent 必须声明为接口,而不是 type 如果你想使用 extends 语法.
It does not work the other way round - UserEvent must be declared as interface, not a type if you want to use extends syntax.
而且仍然无法使用 extend 任意类型 - 例如,如果 Event 是没有任何约束的类型参数,则它不起作用.
And it's still impossible to use extend with arbitrary types - for example, it does not work if Event is a type parameter without any constraints.
更多推荐
可以在 Typescript 中扩展类型吗?
发布评论