从自定义React Native库导入类型时类型检查失效
自定义React Native组件库类型检查失效的解决方法
我在开发React Native组件库时,定义了CustomTheme类型供应用侧覆写主题使用,但应用中导入该类型后,VSCode不会提示对象缺少属性,类型检查完全失效。以下是相关代码和配置,以及对应的解决步骤:
库中相关文件
src/types/CustomTheme.ts
declare type CustomTheme = { dark: boolean; colors: { primary: string; background: string; card: string; text: string; textOnPrimary: string; border: string; variant: string; notification: string; inversed: string; }; text: { lg: number; med: number; sm: number; }; }; export default CustomTheme;
src/index.tsx
// Types for theme import type CustomTheme from './types/CustomTheme'; export type { CustomTheme };
应用侧使用代码
import { type CustomTheme } from 'my-library'; let CustomLightTheme: CustomTheme = { // VSCode未提示缺少属性,类型检查失效 };
库的配置文件
package.json
{ "name": "mr-design", "version": "0.1.1", "description": "A react-native components library", "source": "./src/index.tsx", "main": "./lib/commonjs/index.js", "module": "./lib/module/index.js", "types": "./lib/typescript/src/index.d.ts", "exports": { ".": { "types": "./lib/typescript/src/index.d.ts", "import": "./lib/module/index.js", "require": "./lib/commonjs/index.js" } } }
tsconfig.json
{ "compilerOptions": { "rootDir": ".", "paths": { "mcomponents": ["./src/index"] }, "allowUnreachableCode": false, "allowUnusedLabels": false, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "jsx": "react-jsx", "lib": ["ESNext"], "module": "ESNext", "moduleResolution": "Bundler", "noFallthroughCasesInSwitch": true, "noImplicitReturns": true, "noImplicitUseStrict": false, "noStrictGenericChecks": false, "noUncheckedIndexedAccess": true, "noUnusedLocals": true, "noUnusedParameters": true, "resolveJsonModule": true, "skipLibCheck": true, "strict": true, "target": "ESNext", "verbatimModuleSyntax": true, "declaration": true } }
解决步骤
1. 修正类型导出方式
原代码中用declare type结合默认导出的方式,容易在二次导出时出现类型丢失。改成命名导出:
// src/types/CustomTheme.ts export type CustomTheme = { dark: boolean; colors: { primary: string; background: string; card: string; text: string; textOnPrimary: string; border: string; variant: string; notification: string; inversed: string; }; text: { lg: number; med: number; sm: number; }; };
然后在入口文件中直接导入并导出命名类型:
// src/index.tsx import type { CustomTheme } from './types/CustomTheme'; export type { CustomTheme };
2. 确保类型声明文件正确生成
在tsconfig.json中显式指定类型声明文件的输出目录,避免路径混乱:
{ "compilerOptions": { // ...其他原有配置 "declaration": true, "declarationDir": "./lib/typescript" } }
该配置会把生成的.d.ts文件集中放在lib/typescript目录,和package.json中types字段的路径对应。
3. 验证打包后的类型文件
执行打包命令后,查看./lib/typescript/src/index.d.ts文件,确认CustomTheme类型是否完整导出。如果类型文件中没有该定义,需要检查打包工具(如tsup、rollup)的配置,确保它能正确处理TypeScript类型声明的生成。
4. 应用侧重新安装验证
删除应用目录下的node_modules和锁文件,重新安装组件库:
rm -rf node_modules package-lock.json npm install
此时在应用代码中使用CustomTheme类型,VSCode应该会正确提示对象缺少的属性,类型检查生效。
内容的提问来源于stack exchange,提问作者Mirecos
相关产品推荐
相关产品推荐

