declare关键字
1 2 3 4 5 6 7 8
| declare var 声明全局变量 declare function 声明全局方法 declare class 声明全局类 declare enum 声明全局枚举类型 declare namespace 声明(含有子属性的)全局对象 declare module 声明模块 interface 和 type 声明全局类型 /// <reference /> 三斜线指令
|
使用declare定义类型后,编码时就能得到代码提示
声明文件
当使用第三方库时,需要引用它的声明文件,才能获得对应的代码补全、接口提示等功能
有的库自带声明文件,但有的不带,引用不带声明文件的库时,TS会报错

TS社区的人会为一些知名JS库贡献声明文件,可以直接引入
1
| npm install @types/[库名] -D
|
如果确实没有声明文件,可以自己定义一个
定义声明文件
在express.d.ts中使用declare module定义express模块的类型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| declare module "express" { interface Router { get(path:string,cb:(req:any,res:any)=>void):void } interface App { use(path:string,router:any):void listen(port:number,cb?:()=>void) } interface Express { ():App Router():Router }
const express:Express export default express }
|