声明文件 .d.ts 是做什么的?如何让 TS 识别没有类型的第三方库?

.d.ts 只含类型声明、不含实现,用来给 JS 代码或第三方库补充类型信息(不会生成运行时代码)。

// 为无类型库写声明
declare module 'legacy-lib' {
  export function doThing(input: string): number
}

来源优先级:

  1. 库自带 types / @types/xxx(如 @types/lodash)
  2. 项目 *.d.ts(全局 declare 或 declare module)
  3. 找不到时把 noImplicitAny 放宽或临时 const x: any = require('lib')

@types 由 DefinitelyTyped 社区维护;自己写库时可用 tsc --declaration 自动生成 .d.ts。

同分类其他题目