ChatGPT解决这个技术问题 Extra ChatGPT

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?

The type keyword is used to define type aliases, not interfaces or classes.

A
AndreM96

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.


I am using TS v3.5.2, and I am not able to have an interface extend a type. interface A<T> extends B<T> {blar} An interface can only extend an object type or intersection of object types with statically known members
@WORMSS doing this interface Identifiable<T> extends T { id: string } gives me error "An interface can only extend an object type or intersection of object types with statically known members.ts(2312)"
As typeScript is structurally typed, vs nominally, extending an 'arbitrary type' that has no further structure (constraints) will likely always be impossible.
C
Community

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

This is a great solution. I'm working in React Native and this allows me to easily extend TextInputProps for my own custom text entry component. Thanks!
C
Community

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.


Yeah, but I don't like the word interface when I actually mean a type
Fair enough, then artem's answer should suit you :)
a
aegatlin

A generic extension type can be written as follows:

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