简体   繁体   English

可以在 Typescript 中扩展类型吗?

[英]Possible to extend types in Typescript?

Say I have the following type:假设我有以下类型:

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

I now want to extend this type, ie我现在想扩展这种类型,即

type UserEvent extends Event = {
   UserId: string; 
}

This doesn't work.这行不通。 How can I do this?我怎样才能做到这一点?

The keyword extends can be used for interfaces and classes only.关键字extends只能用于接口和类。

If you just want to declare a type that has additional properties, you can use intersection type :如果您只想声明具有附加属性的类型,可以使用交集类型

type UserEvent = Event & {UserId: string}

UPDATE for TypeScript 2.2, it's now possible to have an interface that extends object-like type , if the type satisfies some restrictions: TypeScript 2.2 的更新,如果类型满足一些限制,现在可以有一个扩展类对象类型的接口

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

interface UserEvent extends Event {
   UserId: string; 
}

It does not work the other way round - UserEvent must be declared as interface, not a type if you want to use extends syntax.相反,它不起作用 - 如果要使用extends语法,则必须将UserEvent声明为接口,而不是type

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.并且仍然不可能对任意类型使用extend - 例如,如果Event是没有任何约束的类型参数,它就不起作用。

you can intersect types:你可以相交类型:

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

somewhere in you code you can now do:您现在可以在代码中的某处执行以下操作:

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

What you are trying to achieve is equivalent to您要达到的目标相当于

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

interface UserEvent extends Event {
   UserId: string; 
}

The way you defined the types does not allow for specifying inheritance, however you can achieve something similar using intersection types, as artem pointed out.您定义类型的方式不允许指定继承,但是正如artem指出的那样,您可以使用交集类型实现类似的功能。

泛型扩展类型可以写成如下:

type Extension<T> = T & { someExtensionProperty: string }

你也可以这样做:

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

Say I have the following type:说我有以下类型:

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

I now want to extend this type, ie我现在想扩展这种类型,即

type UserEvent extends Event = {
   UserId: string; 
}

This doesn't work.这是行不通的。 How can I do this?我怎样才能做到这一点?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM