HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Possible to extend types in Typescript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
possibleextendtypestypescript

Problem

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?

Solution

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 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; 
}


It does not work the other way round - UserEvent must be declared as interface, not a type if you want to use extends syntax.

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.

Code Snippets

type UserEvent = Event & {UserId: string}
type Event = {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

Context

Stack Overflow Q#41385059, score: 1471

Revisions (0)

No revisions yet.