Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 621
Kousha Avatar asked Dec 29 '16 18:12

Kousha


People also ask

Can a type extend a type?

Use an intersection type to extend a type in TypeScript, e.g. type TypeB = TypeA & {age: number;} . Intersection types are defined using an ampersand & and are used to combine existing object types. You can use the & operator as many times as necessary to construct a type.

Can we extend interface in TypeScript?

In TypeScript, interfaces can also extend classes, but only in a way that involves inheritance. When an interface extends a class, the interface includes all class members (public and private), but without the class' implementations.

Can you extend multiple interfaces TypeScript?

An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.

What does Extends mean in TypeScript?

extends : The child class (which is extended) will inherit all the properties and methods of the class is extends. implements : The class which uses the implements keyword will need to implement all the properties and methods of the class which it implements.


1 Answers

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.

like image 112
artem Avatar answered Sep 22 '22 16:09

artem