如何在.d.ts源项目中提前检测索引签名的类型错误?
Project-A的index.d.ts里定义了带索引签名的接口:
interface FuncOpts { foo?: string; bar?: number; pro?: boolean; [key: string]: string | number | boolean; }
单独执行tsc index.d.ts时无编译错误,但当Project-B依赖Project-A执行tsc编译时,会触发TS2411错误:
../project-a/index.d.ts:2:3 - error TS2411: Property 'foo' of type 'string | undefined' is not assignable to 'string' index type 'string | number | boolean'.
2 foo?: string;
~~~../project-a/index.d.ts:3:3 - error TS2411: Property 'bar' of type 'number | undefined' is not assignable to 'string' index type 'string | number | boolean'.
3 bar?: number;
~~~../project-a/index.d.ts:4:3 - error TS2411: Property 'pro' of type 'boolean | undefined' is not assignable to 'string' index type 'string | number | boolean'.
4 pro?: boolean;
~~~
需要在Project-A编译阶段就检测出这类错误,避免等到依赖项目编译时才暴露问题。
问题根源
- 带
?的可选属性实际类型是「属性类型 + undefined」,比如foo?: string等价于foo: string | undefined - 接口的索引签名只包含
string | number | boolean,未覆盖undefined,导致类型不兼容 - 单独编译单个
.d.ts文件时,TypeScript默认检查规则不严格,不会触发错误;但项目级编译(尤其是依赖场景)会严格校验类型匹配
解决办法
1. 修正接口定义
有两种可行的修正方式:
方式一:将undefined加入索引签名类型
直接扩展索引签名的类型范围,使其包含可选属性的undefined:
interface FuncOpts { foo?: string; bar?: number; pro?: boolean; [key: string]: string | number | boolean | undefined; }
方式二:拆分接口(无需通过索引访问固定属性时适用)
如果不需要通过字符串索引访问foo、bar、pro这些固定属性,可以把接口拆分为两部分,用交叉类型合并:
interface FuncOptsBase { foo?: string; bar?: number; pro?: boolean; } interface FuncOptsIndex { [key: string]: string | number | boolean; } type FuncOpts = FuncOptsBase & FuncOptsIndex;
2. 在Project-A开启严格编译检测
要让Project-A自身编译时就能发现错误,不能仅编译单个文件,需配置tsconfig.json启用严格检查:
创建或修改Project-A的tsconfig.json:
{ "compilerOptions": { "strict": true, "declaration": true, "skipLibCheck": true }, "include": ["index.d.ts"] }
然后执行tsc(而非tsc index.d.ts)进行项目级编译,此时TypeScript会严格校验接口的类型兼容性,提前抛出TS2411错误。
内容的提问来源于stack exchange,提问作者LiHS

