javascript 找不到与'displayName'匹配的TypeScript类型作为'type'的属性

o75abkj4  于 2023-03-16  发布在  Java
关注(0)|答案(3)|浏览(107)

正如标题所述,我找不到正确的类型。我已经检查了DevTools和我正在以编程方式查看的每个组件都有Component.type.displayNametype表示任何不是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;

最后一行取自Reactrepo。所以我知道它是有效的。

node在VS代码中为:

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'.
ia2d9nvy

ia2d9nvy1#

您可以使用以下内容:

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;
}
ojsjcaue

ojsjcaue2#

我想我解决了:

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);
}
idfiyjo8

idfiyjo83#

尝试使用Component.type.name而不是Component.type.displayName

相关问题