Search code examples
javascriptreactjstypescriptinterfacereact-props

How to define interfaces in TypeScript to pass the props correctly?


I have a simple component which renders a logo text

interface AppBarLogoProps = {
  logo: string;
};

export const AppBarLogo: FC<AppBarLogoProps> = ({ logo }) => {
  return (
    <>
      <h1>
        {logo}
      </h1>
    </>
  );
};

and the AppBarTop component which is more complex than below, but the idea is that I want to pass the logo prop from AppBarTop to AppBarLogo.

The problem is that I have to use logo.logo notation. How should I define interfaces to use return <AppBarLogo logo={logo} /> instead of return <AppBarLogo logo={logo.logo} /> ?

interface AppBarTopProps {
  logo: AppBarLogoProps;
}

export const AppBarTop: FC<AppBarTopProps> = ({ logo }) => {
   return <AppBarLogo logo={logo.logo} />
}


Solution

  • You can use TypeScript intersection &:

    interface AppBarLogoProps {
      logo: string;
    };
    
    interface AppBarTopProps {
      foo: string
    }
    
    export const AppBarTop: React.FC<AppBarTopProps & AppBarLogoProps> = ({ logo, foo }) => {
      return <AppBarLogo logo={logo} />
    }
    

    Also, you should probably not use FC and simply use function:

    export const AppBarTop2 = ({ logo, foo }: AppBarTopProps & AppBarLogoProps) => {
      return <AppBarLogo logo={logo} />
    }