TypeScript学习笔记(十二)—— 类型声明文件第三方库

440 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第4天,点击查看活动详情

前言

大家好呀,我是L同学。在上篇文章TypeScript学习笔记(十一)—— 类型声明文件中,我们学习了TypeScript的相关知识点,包括什么是tsconfig、ts中的类型声明文件等相关知识点。在本篇文章中,我们将学习TypeScript的相关知识点,包括类型声明文件-第三方库,类型声明文件-自定义等内容。

类型声明文件-第三方库

目前,几乎所有常用的第三方库都有相应的类型声明文件。第三方库的类型声明文件有两种存在形式:1 库自带类型声明文件 2 由 DefinitelyTyped 提供。

  1. 库自带类型声明文件:比如,axios。我们可以查看 node_modules/axios 目录。这种情况下,正常导入该库,TS 就会自动加载库自己的类型声明文件,以提供该库的类型声明。

  2. 由 DefinitelyTyped 提供。DefinitelyTyped 是一个 github 仓库,用来提供高质量 TypeScript 类型声明。可以通过 npm/yarn 来下载该仓库提供的 TS 类型声明包,这些包的名称格式为:@types/*,比如,@types/react、@types/lodash 等。在实际项目开发时,如果你使用的第三方库没有自带的声明文件,VSCode 会给出明确的提示。当安装 @types/* 类型声明包后,TS 也会自动加载该类声明包,以提供该库的类型声明。TS 官方文档提供了一个页面,可以来查询 @types/* 库。

类型声明文件-自定义

如果多个 .ts 文件中都用到同一个类型,此时可以创建 .d.ts 文件提供该类型,实现类型共享。

操作步骤:

  1. 创建 index.d.ts 类型声明文件。
  2. 创建需要共享的类型,并使用 export 导出(TS 中的类型也可以使用 import/export 实现模块化功能)。
  3. 在需要使用共享类型的 .ts 文件中,通过 import 导入即可(.d.ts 后缀导入时,直接省略)。

在TS 项目中也可以使用 .js 文件。在导入 .js 文件时,TS 会自动加载与 .js 同名的 .d.ts 文件,以提供类型声明。

declare 关键字:用于类型声明,为其他地方(比如,.js 文件)已存在的变量声明类型,而不是创建一个新的变量。

  • 对于 type、interface 等这些明确就是 TS 类型的(只能在 TS 中使用的),可以省略 declare 关键字。
  • 对于 let、function 等具有双重含义(在 JS、TS 中都能用),应该使用 declare 关键字,明确指定此处用于类型声明。
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)
}

export { count, songName, position, add, changeDirection, fomartPoint }

定义类型声明文件。

declare let count:number

declare let songName: string

interface Position {
  x: number,
  y: number
}

declare let position: Position

declare function add (x :number, y: number) : number

type Direction = 'left' | 'right' | 'top' | 'bottom'

declare function changeDirection (direction: Direction): void

type FomartPoint = (point: Position) => void

declare const fomartPoint: FomartPoint

export {
  count, songName, position, add, changeDirection, FomartPoint, fomartPoint
}