Search code examples
javascriptreactjstypescriptinterface

How to reuse interface defined in typescript


I have an existing interface for legacy env

export interface ITForm {
    formDescription: string;
    formId: string;
    isForm: boolean;
    include?: boolean;
}

Now, I need a interface for new env, which doesn't need formId/isForm/include, only formDescription is the common attribute and formDescription/type/route are mandatory fields

   export interface ITFormNew {
        formDescription: string;
        type: string;
        route: string;
    }

May I please know is it a good practise to use two interfaces defined above or we can reuse the existing interface to cater for the new one as well? Thanks.


Solution

  • You can use the typescript utility type Pick or Omit

    export interface ITFormNew extends Pick<ITForm, "formDescription"> {
            type: string;
            route: string;
    }
    

    View on TS Playground

    As for whether this is good practice, imho it creates a single source of truth and is more useful on more complex shared types.