导入自定义字体(如Google Font)时如何解决TypeScript报错问题
Got it, let's fix that TypeScript error you're hitting when adding Google Fonts (or other custom fonts) with the preconnect link. Here's what's going on and how to resolve it:
问题根源
The error Type 'boolean' is not assignable to type 'string'.ts(2322) comes from two mismatches with TypeScript's type definitions for <link> elements (from LinkHTMLAttributes<HTMLLinkElement>):
- You’re using the lowercase
crossoriginattribute, but the official type expectscrossOrigin(note the capitalized "O"). - Writing
<... crossOrigin />gets interpreted as a boolean value (true) by React/TypeScript, but thecrossOriginproperty requires a string type.
修复方案
Fix the attribute name and value type
- First, switch to the camelCase attribute name:
crossOrigin(notcrossorigin) to align with TypeScript's type rules. - Then, replace the boolean shorthand with a valid string value. For font preconnect, the most common and recommended value is
anonymous:
If your use case requires sending credentials with the request, you can use<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />crossOrigin="use-credentials"instead.
- First, switch to the camelCase attribute name:
Leverage Next.js's built-in optimization (for Next.js projects)
- Starting with Next.js v10.2, the framework includes native Web Font Optimization. You can completely remove that preconnect
<link>tag — your fonts will still load correctly, and this TypeScript error will vanish without any extra code changes.
- Starting with Next.js v10.2, the framework includes native Web Font Optimization. You can completely remove that preconnect
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

