文章目录
TS 类型声明文件:用来为已存在的 JS 库提供类型信息。类型声明文件可以让我们不需要将JS重构为TS,就可以像用 TS 一样,有代码提示、类型保护等机制。
TS文件类型
TS 中有两种文件类型:1 .ts 文件 2 .d.ts 文件
- .ts 文件:
- .ts 是 implementation(代码实现文件);
- 既包含类型信息又可执行代码。
- 先编译为 .js 文件,然后,执行代码。
- 用途:编写程序代码。
- .d.ts 文件:
- .d.ts 是 declaration(类型声明文件)。
- 只包含类型信息的类型声明文件,不能出现可执行代码。
- 不会生成 .js 文件,仅用于提供类型信息。
- 用途:为 JS 提供类型信息。
declare 关键字
declare 是描述 TS 文件之外信息的一种机制,它的作用是告诉 TS 某个类型或变量已经存在,我们可以使用它声明全局变量、函数、类、接口、类型别名、类的属性或方法以及模块与命名空间。
在类型声明文件中,对于 type、interface 等只能在 TS 中使用的关键字,可以省略 declare 关键字;对于 let、function 等在 JS、TS 中都能用的关键字,应该使用 declare 关键字,明确指定此处用于类型声明。
使用已有的类型声明文件
【TS 内置的类型声明文件】
TS 为 JS 运行时可用的所有标准化内置 API 都提供了声明文件。
比如,在使用数组时,数组所有方法都会有相应的代码提示以及类型信息。
可以通过 Ctrl + 鼠标左键 来查看内置类型声明文件内容。
例如,forEach 方法的类型声明,在(lib.es5.d.ts)类型声明文件中。像 window、document 等 BOM、DOM API 也都有相应的类型声明(lib.dom.d.ts)。
【第三方库的类型声明文件】
目前,几乎所有常用的第三方库都有相应的类型声明文件。
第三方库的类型声明文件有两种存在形式:
1. 库自带类型声明文件:比如,axios。
2. 由 DefinitelyTyped 提供。https://github.com/DefinitelyTyped/DefinitelyTyped/
DefinitelyTyped 是一个 github 仓库,用来提供高质量 TypeScript 类型声明。
可以通过命令 npm i -D @types/包名 来下载该仓库提供的 TS 类型声明包。安装后,TS 也会自动加载该类声明包,以提供该库的类型声明。
创建类型声明文件
操作步骤:
- 创建 ***.d.ts 类型声明文件。
- 创建需要共享的类型,并使用 export 导出(TS 中的类型也可以使用 import/export 实现模块化功能)。
- 在需要使用共享类型的 .ts 文件中,通过 import 导入即可,导入时不加后缀 .ts(.d.ts 导入时,若路径下无同名 .ts 文件,后缀 .d 也可以省略(反例:demo.d.ts 和 demo.ts))。
index.d.ts
/*【index.d.ts】*/
type Props = { x: number; y: number }
export { Props }
demo.ts
/*【demo.ts】*/
import { Props } from './index';
let p1: Props = { x: 1, y: 2 }
// 同名情况
import { Point } from './demo.d';
let p2: Point = { x: 1, y: 2 }
为已有 JS 文件提供类型声明
将 JS 项目迁移到 TS 项目时,为了让已有的 .js 文件有类型声明,可以根据已有 js 脚本编写 .ts 类型声明文件。
utils.d.ts
// 为 utils.js 文件来提供类型声明
declare let count: number
declare let songName: string
interface Point {
x: number
y: number
}
declare let position: Point
declare function add(x: number, y: number): number
declare function changeDirection(
direction: 'up' | 'down' | 'left' | 'right'
): void
type FomartPoint = (point: Point) => void
declare const fomartPoint: FomartPoint
// 注意:类型提供好以后,需要使用 模块化方案 中提供的
// 模块化语法,来导出声明好的类型。然后,才能在
// 其他的 .ts 文件中使用
export { count, songName, position, add, changeDirection, fomartPoint, Point }
utils.js
let count = 10
let songName = '大鱼'
let position = {
x: 0,
y: 0
}
function add(x, y) {
return x + y
}
function changeDirection(direction) {
console.log(direction)
}
const fomartPoint = point => {
console.log('当前坐标:', point)
}
module.exports = { count, songName, position, add, changeDirection, fomartPoint }
demo.ts
.ts 文件在导入 .js 文件时,会自动加载与 .js 同名的 .d.ts 文件,以提供类型声明。
import { count, songName, add, Point } from './utils'
let p1: Point = {
x: 10,
y: 20
}
// 使用js方法变量
console.log('count', count); // count 10
console.log('songName', songName); // songName 大鱼
console.log('add()', add(1, 4)); // add() 5