Home > Software design >  How to add type to prop using react typescript?
How to add type to prop using react typescript?

Time:10-08

I am using last version of typescript. I want to add type to prop.

const const SideBar = (props) => <div id="SideBar" {...props} />;

How to add. this props type ?

CodePudding user response:

Add an interface before the function:

interface SideBarProps {
 element: HTMLElement;
}

const SideBar = (props: SideBarProps) => <div id="SideBar" {...props} />;

CodePudding user response:

Have you tried to specify the type as usual? const SideBar = (props: Type) => <div id="SideBar" {...props} />

CodePudding user response:

I'm using two methods for this: type and interface. There are minor differences between these two.

Using type

type SidebarProps = {
   prop1: string;
   prop2: boolean;
}

const Sidebar = (props: SidebarProps) => <div id="SideBar" {...props} />;

Using interface

interface SidebarProps {
   prop1: string,
   prop2: boolean
}

const Sidebar = (props: SidebarProps) => <div id="SideBar" {...props} />;

CodePudding user response:

The type is HTMLDivElement


const Sidebar = (props: Htmldivelement) => <div id="SideBar" {...props} />;
  • Related