# 十八.类型声明
前言
declare关键字用来告诉编译器,某个类型是存在的,可以在当前文件中使用
# 1.声明全局变量
# 1.1 普通类型声明
- xxx.d.ts
declare let age: number
declare function sum(a: string, b: string): void
declare class Animal {}
declare const enum Seaons {
Spring,
Summer,
Autumn,
Winter,
}
declare interface Person {
name: string
age: number
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
类型声明在编译的时候都会被删除,不会影响真正的代码。目的是不重构原有的 js 代码,而且可以得到很好的 TS 支持
- jquery 通过外部 CDN 方式引入,想在代码中直接使用
declare const $: (selector: string) => {
height(num?: number): void
width(num?: number): void
}
1
2
3
4
2
3
4
$("target").height()
1
*.d.ts中 直接写 type 、interface 加上 declare 和 不加 declare是一样的效果。都能在其他ts文件 直接引用
# 1.2 命名空间声明
declare namespace jQuery {
function ajax(url: string, options: object): void
namespace fn {
function extend(obj: object): void
}
}
jQuery.ajax("/", {})
jQuery.fn.extend({})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
namespace 表示一个全局变量,包含很多子属性,命名空间内部不需要使用 declare 声明属性或方法
# 2.类型声明文件
类型声明文件以.d.ts
结尾。默认在项目编译时会查找所有以.d.ts
结尾的文件
- declare var 名称: 变量
- declare const / let 名称: ES6变量
- declare function 名称: 方法
- declare class 名称: 类
- declare enum 名称: 枚举
- declare module 名称: 模块
- declare namespace 名称: 命名空间
- declare interface 名称: 接口
- declare type 名称: 类型别名
declare const $:(selector:string) => {
height(num?number):void
width(num?number):void
}
declare namespace jQuery {
function ajax(url:string,options:object):void
namespace fn {
function extend(obj:object):void
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
.d.ts中 namespace定义时,必须加上:declare ,否则报错:.d.ts 文件中的顶级声明必须以 "declare" 或 "export" 修饰符开头
# 3.编写第三方声明文件
配置 tsconfig.json
- jquery 声明文件
"moduleResolution": "node",
"baseUrl": "./",
"paths": {
"*": ["types/*"]
},
1
2
3
4
5
2
3
4
5
declare function jQuery(selector: string): HTMLElement
declare namespace jQuery {
function ajax(url: string): void
}
export = jQuery
1
2
3
4
5
2
3
4
5
- events 模块声明文件
import { EventEmitter } from "events"
var e = new EventEmitter()
e.on("message", function (text) {
console.log(text)
})
e.emit("message", "hello")
1
2
3
4
5
6
2
3
4
5
6
export type Listener = (...args: any[]) => void
export type Type = string | symbol
export class EventEmitter {
static defaultMaxListeners: number
emit(type: Type, ...args: any[]): boolean
addListener(type: Type, listener: Listener): this
on(type: Type, listener: Listener): this
once(type: Type, listener: Listener): this
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 4.模块导入导出
import $ from "jquery" // 只适用于 export default $
const $ = require("jquery") // 没有声明文件可以直接使用 require语法
import * as $ from "jquery" // 为了支持 Commonjs规范 和 AMD规范 导出时采用export = jquery
import $ = require("jquery") // export = jquery 在commonjs规范中使用
1
2
3
4
5
6
7
2
3
4
5
6
7
# 5.第三方声明文件
@types 是一个约定的前缀,所有的第三方声明的类型库都会带有这样的前缀
npm install @types/jquery -S
1
当使用 jquery 时默认会查找 node_modules/@types/jquery/index.d.ts 文件
- 查找规范
- node_modules/jquery/package.json 中的 types 字段
- node_modules/jquery/index.d.ts
- node_modules/@types/jquery/index.d.ts