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

基于配置动态构建Preact路由时出现TypeScript错误求助

多语言Preact路由配置的TypeScript错误解决

我正在测试多语言配置,每个国家对应不同根目录,希望构建Preact路由时引用代码配置信息。

关键代码片段

import { configuration } from "./components/configuration";
import { Router, lazy } from "preact-iso";

const Home = lazy(() => import("./pages/public/Home"));

return (
  <Router>
    {
      configuration.countries.map((country) => (
        <Home path={country.rootPath} culture={country.culture} />
      ))
    }
  </Router>
);

问题现象

路由功能正常,但出现TypeScript错误:

Type 'Element[]' is missing the following properties from type 'VNode<{}>': type, props, key ts(2739)

补充说明

简化Home组件代码后问题仍存在:

import { h, FunctionComponent } from "preact";

interface Props {
    culture: string;
};

const Home: FunctionComponent<Props> = ({ culture }) => {
    return (
        <h1>Home {culture}</h1>
    );
};

export default Home;

解决方案

问题根源

  1. map生成的元素列表缺少唯一key属性,Preact要求列表渲染的元素必须有唯一key,TypeScript也会因此无法正确推断类型
  2. Home组件的Props接口未包含路由传递的path属性,存在类型不匹配
  3. Router组件对子元素的类型校验要求严格,无key的数组无法被识别为合法子元素集合

修改后的代码

路由部分

import { configuration } from "./components/configuration";
import { Router, lazy } from "preact-iso";

const Home = lazy(() => import("./pages/public/Home"));

return (
  <Router>
    {configuration.countries.map((country) => (
      <Home 
        key={country.culture} // 添加唯一key,可用country.rootPath或其他唯一标识
        path={country.rootPath} 
        culture={country.culture} 
      />
    ))}
  </Router>
);

Home组件部分

import { h, FunctionComponent } from "preact";

interface Props {
    culture: string;
    path?: string; // 补充路由传递的path属性
};

const Home: FunctionComponent<Props> = ({ culture }) => {
    return (
        <h1>Home {culture}</h1>
    );
};

export default Home;

说明

  • 添加key后,TypeScript能正确识别数组元素为合法VNode,同时避免Preact列表渲染的性能问题
  • 补充path属性到Props接口,消除类型不匹配的潜在问题
  • 路由功能本身正常是因为Preact运行时对类型要求宽松,但TypeScript的静态检查会严格校验类型一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:08:17