ค้นหาเว็บไซต์

reactjs - วิธีประกาศประเภทอย่างถูกต้องสำหรับคอมโพเนนต์ห่อของ React (HOC) โดยใช้ Typescript


ฉันกำลังพยายามที่จะสร้าง HOC ง่ายๆ สำหรับเพิ่มความสามารถให้กับคอมโพเนนต์ด้วย tooltip แบบกำหนดเอง แม้ว่ารหัสจะทำงานได้ดี แต่ฉันไม่สามารถหาวิธีประกาศชนิดข้อมูลได้อย่างถูกต้อง เวอร์ชันที่เรียบง่ายของ HOC ของฉันมีลักษณะดังนี้:

const withTooltip = <P extends {}>(
  BaseComponent: React.ComponentType<P>
): React.FC<P & { title?: string }> => ({ title, ...rest }) => {
  
  return (
    <>
      <BaseComponent {...rest} />
      <Tooltip title={title}/>
    </>
  );
};

แต่ฉันได้รับข้อผิดพลาด Typescript:

Type 'Omit<PropsWithChildren<P & { title?: string | undefined; }>, "title">' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
  Type 'Omit<PropsWithChildren<P & { title?: string | undefined; }>, "title">' is not assignable to type 'P'.
    'Omit<PropsWithChildren<P & { title?: string | undefined; }>, "title">' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint '{}'.

ฉันจะประกาศชนิดข้อมูลสำหรับ HOC แบบนี้อย่างถูกต้องได้อย่างไร?

คำตอบ #1

คุณจำเป็นต้องใช้ประเภทของ props rest ที่ถูกสืบทอด:

import React, { ComponentType } from 'react'

const Tooltip = (props: { title?: string }) => null

type OptionalTitle = { title?: string };

const withTooltip = <P extends object = object>(
  BaseComponent: ComponentType<Omit<P & OptionalTitle, "title">>
): React.FC<P & OptionalTitle> => ({ title, ...rest }) => {

  return (
    <>
      <BaseComponent {...rest} />
      <Tooltip title={title} />
    </>
  );
};

บทความที่เกี่ยวข้อง