typescripttypescript-generics

Extend/Omit interface in typescript


I have list of props under interface type. And want to extend interface type with modification as below,

  1. Change of Prop types

  2. addition of new fields

     interface Request {
       Id: NullProp<number>,
       Name: NullProp<string>,
       Code: NullProp<string>,
       Type: NullProp<string>,
       ValueType: NullProp<string>
     .....
     ...
     }
    

    /* trying to achieve like below */

         interface DataRequest extends Request {
           Id: number,
           Name: string,
           Code: string,
           Type: string,
           ValueType: string,
         .....
         ...,
           DataRequestId: number,
           DataRequestType: string
           DataValueType: NullProp<string>
         }
    

As found, we can do 'Omit' on derived interface but it will need long list of props as I have many interfaces like that and need to extend similar one. Could you please advise if this should be separate new interface and duplicating props OR any way to extend same interface ?


NullProp , type for Q | null | undefined


Solution

  • You can strip away the NullProps into a separate type:

    type RemoveNullProp<T> = T extends NullProp<infer V> ? V : T;
    
    type RequestWithoutNullProp = {
      [k in keyof Request]: RemoveNullProp<Request[k]>
    }
    

    and then extend that type with your extra properties:

    interface DataRequest extends RequestWithoutNullProp {
      DataRequestId: number;
      DataRequestType: string;
      DataValueType: NullProp<string>;
    }