Search code examples
typescriptreact-typescript

Extend TypeScript type with different variable names


I am trying to extend a TypeScript type that that is used for the props of a React component.

type myType = {  // this is imported from another file
  variable1: string;
  variable2: boolean;
};

interface  myInterface extends myType {
  anExtraVariable: string;
}

const myComponent: React.FC<myInterface> = ({ differentVariable1, differentVariable2, anExtraVariable }) => {
  return (...);
};

differentVariable1 and differentVariable2 have the same type as variable1 and variable2 from myType.

Any help would be appreciated.


Solution

  • Did you try define the type of your different variables when you extend myType?

    Example:

    interface myInterface extends myType {
     differentVariable1: myType['variable1']; // Uses the type of 'variable1' from myType
     anExtraVariable: string; 
    }