可以在Typescript中扩展类型吗?

2022-08-29 23:08:58

假设我有以下类型:

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

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

type UserEvent extends Event = {
   UserId: string; 
}

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


答案 1

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

如果只想声明具有其他属性的类型,则可以使用交集类型

type UserEvent = Event & {UserId: string}

对于 TypeScript 2.2 的更新,如果类型满足一些限制,现在可以有一个扩展类似对象类型的接口

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

interface UserEvent extends Event {
   UserId: string; 
}

相反,它不能反过来工作 - 必须声明为接口,而不是如果要使用语法,则不能声明为接口。UserEventtypeextends

它仍然不可能与任意类型一起使用 - 例如,如果是没有任何约束的类型参数,则它不起作用。extendEvent


答案 2

您可以与类型相交:

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

您现在可以在代码中的某个位置执行以下操作:

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