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

Astro + Preact中如何声明SVG组件的Props类型?

Astro SVG组件Props类型声明错误修复方案

问题代码

---
import type { SVGProps } from "preact/compat";

interface Props extends SVGProps<SVGElement> {
  class?: string;
}

const { class: className, ...props } = Astro.props;
---

<svg
  xmlns="http://www.w3.org/2000/svg"
  viewBox="0 0 87 97"
  class={className}
  fill="none"
  {...props}
>

错误信息

Type 'string | SignalLike<string | undefined> | undefined' is not assignable to type 'string | null | undefined'.
  Type 'SignalLike<string | undefined>' is not assignable to type 'string'.ts(2322)
astro-jsx.d.ts(1318, 3): The expected type comes from property 'xmlns' which is declared here on type 'SVGAttributes'
(property) astroHTML.JSX.SVGAttributes.xmlns?: string | null | undefined

问题原因

Astro的Astro.props可能包含响应式信号(SignalLike类型),但你继承的Preact SVGProps<SVGElement>未适配该类型,导致展开props时与SVG原生属性类型冲突。

修复方法

方案1:使用Astro官方SVG类型(推荐)

直接导入Astro内置的SVGAttributes定义Props,它已适配Astro的响应式系统:

---
import type { SVGAttributes } from 'astro/types';

interface Props extends SVGAttributes<'svg'> {
  class?: string;
}

const { class: className, ...props } = Astro.props as Props;
---

<svg
  xmlns="http://www.w3.org/2000/svg"
  viewBox="0 0 87 97"
  class={className}
  fill="none"
  {...props}
>

方案2:类型断言兼容响应式信号

如果需要保留Preact类型,可通过类型断言明确Astro.props的类型:

---
import type { SVGProps } from "preact/compat";

interface Props extends SVGProps<SVGElement> {
  class?: string;
}

// 添加类型断言,明确Props类型
const { class: className, ...props } = Astro.props as Props;
---

<svg
  xmlns="http://www.w3.org/2000/svg"
  viewBox="0 0 87 97"
  class={className}
  fill="none"
  {...props}
>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 06:42:17