reactjs - Typescript React: Hur man deklarerar typer för ett specifikt element som är Props


Jag vill deklarera typer för ett specifikt element, något som <button> eller <input>. men jag kan inte kontrollera ett specifikt element med typ

Här är exempel,

interface Props{
  component: React.ComponentProps<"button"> | never;
};

const TestComponent = (props: Props) =>{
  const {component} = props;
  return <div>{component}</div>
}

const OnlyButtonComponent = () => {
  return(
    <>
      {/** This will be Okay. */}
      <TestComponent component={<button>its button</button>} />
      {/** This must occur error */}
      <TestComponent component={<div>its not button</div>} />
    </>
  )
}

MEN, båda av TestComponent renderas utan fel.

Hur kan jag skydda detta med typdeklaration?

Svar #1

Prova detta

interface Props{
  component: React.ReactNode
};