You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为link标签添加fetchPriority属性时TypeScript报错求解决

解决React中Link标签添加fetchPriority属性的TypeScript类型错误

问题描述

给<link>标签添加fetchPriority属性时触发TypeScript类型错误,相关代码、报错及类型定义情况如下:

示例代码

const optionalPreload = ServerOnlyHead ? (
  <ServerOnlyHead
    children={
      <link
        fetchPriority="high" // 报错位置
        rel="preload"
        as="image"
        href={image?.src || ""}
      />
    }
  />
) : null;

报错信息

Type '{ fetchPriority: string; rel: string; as: string; href: string; }' is not assignable to type 'DetailedHTMLProps<LinkHTMLAttributes<HTMLLinkElement>, HTMLLinkElement>'.
  Property 'fetchPriority' does not exist on type 'DetailedHTMLProps<LinkHTMLAttributes<HTMLLinkElement>, HTMLLinkElement>'.ts(2322)
'fetchPriority' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.ts(7022)

类型定义缺失问题

查看LinkHTMLAttributes接口,确认该属性未被包含:

interface LinkHTMLAttributes<T> extends HTMLAttributes<T> {
        as?: string | undefined;
        crossOrigin?: string | undefined;
        href?: string | undefined;
        hrefLang?: string | undefined;
        integrity?: string | undefined;
        media?: string | undefined;
        imageSrcSet?: string | undefined;
        referrerPolicy?: HTMLAttributeReferrerPolicy | undefined;
        rel?: string | undefined;
        sizes?: string | undefined;
        type?: string | undefined;
        charSet?: string | undefined;
    }

解决方法

1. 升级@types/react至兼容版本

fetchPriority的类型支持在@types/react v18.2.14及以上版本中被添加,直接升级即可让TypeScript自动识别该属性:

npm install @types/react@latest --save-dev
# 或使用yarn
yarn add @types/react@latest --dev

2. 手动扩展LinkHTMLAttributes接口

若无法升级类型包,可通过TypeScript模块扩充功能,在项目中添加该属性的类型定义:

在项目根目录创建或修改react.d.ts文件,添加以下代码:

import 'react';

declare module 'react' {
  interface LinkHTMLAttributes<T> extends HTMLAttributes<T> {
    fetchPriority?: 'high' | 'low' | 'auto';
  }
}

3. 使用类型断言临时绕过检查

如果仅需快速解决问题,可通过类型断言跳过TypeScript的类型检查:

方式一:断言整个link元素的类型

const optionalPreload = ServerOnlyHead ? (
  <ServerOnlyHead
    children={
      <link
        fetchPriority="high"
        rel="preload"
        as="image"
        href={image?.src || ""}
      /> as React.DetailedHTMLProps<React.HTMLProps<HTMLLinkElement>, HTMLLinkElement>
    }
  />
) : null;

方式二:单独断言fetchPriority属性

<link
  {...{ fetchPriority: "high" } as any}
  rel="preload"
  as="image"
  href={image?.src || ""}
/>

内容的提问来源于stack exchange,提问作者Ayyappa Gollu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:30:57