[javascript] 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, i.e.

type UserEvent extends Event = {
   UserId: string; 
}

This doesn't work. How can I do this?

This question is related to javascript typescript

The answer is


May be below approach will be helpful for someone TS with reactjs

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

interface UserEvent<T> extends Event<T> {
    UserId: string;
}

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.


You can also do:

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