جاوااسکریپت - من نمیتوانم نوع TypeScript متناظر برای `displayName` به عنوان یک prop از `type` را پیدا کنم


همانطور که عنوان میگوید، من نمیتوانم نوع صحیح را پیدا کنم. من DevTools را بررسی کردهام و هر مؤلفهای که من به صورت برنامهنویسی بررسی میکنم، دارای Component.type.displayName است. type برای هر چیزی که ElementType نیست، یک تابع است.

نوع نود، نوع بازگشتی برای React.isValidElement است که به این صورت استخراج شده Parameters<typeof React.isValidElement>، زیرا نمیتوانم مطمئن باشم که چیست.

قسمت مشکلساز:

const node = SomeThingUnknown as Parameters<typeof React.isValidElement>;
const type = ((node as unknown) as React.ReactElement<React.FunctionComponent>).type;
const displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;

آخرین خط از مخزن React گرفته شده است. پس میدانم که کار میکند.

node در VS Code، عبارت است از:

const type: string | ((props: any) => React.ReactElement<any, string | ... | (new (props: any) =>
  React.Component<any, any, any>)> | null) | (new (props: any) => React.Component<any, any, any>)

خطا زمانی که موس را روی displayName قرار میدهم، این است:

Property 'displayName' does not exist on type 'JSXElementConstructor<any>'.
  Property 'displayName' does not exist on type '(props: any) =>
    ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null'.

پاسخ شماره ۱

میتوانید از چیزی شبیه به این استفاده کنید:

function getComponentDisplayName(element: React.ReactElement<any>) {
  const node = element as React.ReactElement<React.ComponentType<any>>;
  const type = (node as unknown as React.ReactElement<React.FunctionComponent>)
    .type;
  const displayName =
    typeof type === 'function'
      ? (type as React.FunctionComponent).displayName ||
        (type as React.FunctionComponent).name ||
        'Unknown'
      : type;
  return displayName;
}

پاسخ شماره ۲

فکر میکنم حلش کردم:

export function extractType(node: unknownElement): Function | string {
  return ((node as unknown) as React.ReactElement).type;
}
export function extractDisplayName(type: React.FunctionComponent): string {
  return type.displayName || type.name || "Unknown";
}

پس به آن بگو:

const type = extractType(node);
if (typeof type === "function") {
  const displayName = extractDisplayName((type as unknown) as React.FunctionComponent);
}