Possible to extend types in Typescript?

前端 未结 4 916
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 06:55

Say I have the following type:

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

I now want to extend this type, i

相关标签:
4条回答
  • 2020-12-02 07:26

    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.

    0 讨论(0)
  • 2020-12-02 07:29

    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',
    };
    
    0 讨论(0)
  • 2020-12-02 07:31

    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;
    }
    
    0 讨论(0)
  • 2020-12-02 07:33

    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.

    0 讨论(0)
提交回复
热议问题