可以在Typescript中扩展类型吗? [英] Possible to extend types in Typescript?
本文介绍了可以在Typescript中扩展类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有以下类型:
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 ,现在可以有一个扩展类似对象类型的界面:
type Event = {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
它不起作用 - UserEvent如果要使用
必须声明为接口,而不是 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.
这篇关于可以在Typescript中扩展类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文