TypeScript - 类型声明 Type Declaration

493 阅读1分钟

在实际的项目开发过程中难免会遇到第三方的 npm 模块,而这些 npm 模块并不一定都是通过 TS 编写的,所以说它所提供的成员就不会有强类型的体验。

import { cameCase } from 'lodash' // Could not find a declaration file from module 'lodash'. Try `npm install @types/lodash` if it exists or add a new declaration (.d.ts) file)
declare function camelCase (input: string):string // 类型声明
camelCase('hello typeScript') // (alias) camelCase(input: string):string

类型声明就是一个成员在定义的时候因为种种原因没有声明一个明确的类型,在使用的时候单独为它再做出一个明确的声明。这种用法存在的原因就是为了要考虑兼容一些普通的 JS 模块,由于 TS 的社区非常强大。目前一些绝大多数比较常用的 npm 模块都已经提供了对应的声明,只需要安装一下它所对应的类型声明模块。

// 安装 lodash 所对应的类型声明模块
yarn add @types/lodash -D

总结:在 TS 当中引用第三方模块,如果这个模块当中不包含所对饮的类型声明文件。就可以尝试去安装一个所对应的类型声明模块,这个类型声明模块的形式就是 @types/模块名称 。如果说也没有这样一个对应的类型声明模块,这种情况下就只能够自己使用 declare 语句去声明所对应的模块类型。