1.为何 import axios from 'axios'
安装完直接就能用
axios.get("####").then(res => {
console.log(res)
})
因为它已经在node_module 的axios 的 ##.d.ts 中声明了 axios 变量
2.反之,lodash 安装之后不可以直接只用,还要接着安装 lodash 相关的声明文件才能使用
import lodash from 'lodash'
console.log(lodash.join(["abc", "cba"]))
如果没有安装 lodash 的声明,需要自己在项目中创建声明文件 ##.d.ts,然后手动填写如下code
声明模块
declare module 'lodash' {
export function join(arr: any[]): void
}
声明变量/函数/类
##.d.ts:
declare let whyName: string
declare let whyAge: number
declare let whyHeight: number
declare function whyFoo(): void
declare class Person {
name: string
age: number
constructor(name: string, age: number)
}
main.ts 或者其他 .ts 文件中直接可以使用:
console.log(whyName)
console.log(whyAge)
console.log(whyHeight)
whyFoo()
const p = new Person("why", 18)
console.log(p)
声明文件
在某些情况下,我们也可以声明文件:
- 比如在开发vue的过程中,默认是不识别我们的.vue文件的,那么我们就需要对其进行文件的声明;
- 比如在开发中我们使用了 jpg 这类图片文件,默认typescript也是不支持的,也需要对其进行声明;
##.d.ts:
declare module '*.jpg'
declare module '*.jpeg'
declare module '*.png'
declare module '*.svg'
declare module '*.gif'
other##.ts:
import nhltImage from './img/nhlt.jpg'
声明命名空间
比如我们在index.html中直接引入了jQuery:
pCDN地址: https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js
然后声明下 $,就可以在项目所有文件中使用 $ 了
##.d.ts:
declare namespace $ {
export function ajax(settings: any): any
}
other##.ts:
$.ajax({
})
我们的HTMLImageElement类型来自哪里呢?甚至是document为什么可以有getElementById的方 法呢:
文件 .d.ts 文件,它是用来做类型的声明(declare)。 它仅仅用来做类型检测,告知typescript我们有哪 些类型;
内置类型声明
内置类型声明是typescript自带的、帮助我们内置了JavaScript运行时的一些标准化API的声明文件;
包括比如Math、Date等内置类型,也包括DOM API,比如Window、Document等; n
内置类型声明通常在我们安装typescript的环境中会带有的; phttps://github.com/microsoft/TypeScript/tree/main/lib
外部定义类型声明和自定义声明
外部类型声明通常是我们使用一些库(比如第三方库)时,需要的一些类型声明
这些库通常有两种类型声明方式:
方式一:在自己库中进行类型声明(编写.d.ts文件),比如axios
方式二:通过社区的一个公有库DefinitelyTyped存放类型声明文件
- 该库的GitHub地址:https://github.com/DefinitelyTyped/DefinitelyTyped/
- 该库查找声明安装方式的地址:https://www.typescriptlang.org/dt/search?search=
- 比如我们安装react的类型声明: npm i @types/react --save-dev n
什么情况下需要自己来定义声明文件呢?
- 情况一:我们使用的第三方库是一个纯的JavaScript库,没有对应的声明文件;比如lodash
- 情况二:我们给自己的代码中声明一些类型,方便在其他地方直接进行使用;