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

为何单独文件无法生效React类型扩展配置?

问题原因及解决方案

核心原因

你的自定义React类型扩展未生效,主要是两个关键问题导致:

  1. TypeScript未扫描到自定义类型文件:你的tsconfig.json中include数组仅包含src目录,./@types文件夹不在编译扫描范围内,TypeScript根本不会读取其中的类型定义文件。
  2. 类型扩展文件未被识别为模块:你的配置中开启了isolatedModules模式,该模式要求每个文件必须是模块(包含import/export语句)。如果类型扩展文件没有任何import或export,会被当作全局脚本,无法正确扩展模块类型。

解决方案

步骤1:修改tsconfig.json,将@types加入编译范围

更新include数组,添加./@types,确保TypeScript扫描到自定义类型文件:

{
  "compilerOptions": {
    // 保留原有配置不变
  },
  "include": [
    "src",
    "./@types"
  ]
}

步骤2:确保类型扩展文件是模块

修改./@types/react/index.d.ts,通过以下两种方式之一将文件标记为模块:
方案一(推荐,依赖React类型):

import type React from 'react';

declare module 'react' {
    function memo<A, B>(Component: (props: A) => B): (props: A) => React.ReactElement | null;
}

方案二(无依赖,添加空导出):

declare module 'react' {
    function memo<A, B>(Component: (props: A) => B): (props: A) => React.ReactElement | null;
}

// 空导出,将文件标记为模块
export {};

验证

修改完成后,重启TypeScript语言服务(或IDE),你的React类型扩展即可正常生效,无需再使用内联声明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:15:33