js智能提示工具 — xxx.d.ts文件


 xxx.d.ts语法说明:

【xxx.d.ts 里面的语法 和 ts是一样。会了ts, xxx.d.ts 里面的类型也就看懂了】

一、全局类型

  • 变量

   比如现在有一个全局变量,那对应的d.ts文件里面这样写。

declare var aaa:number

其中关键字declare表示声明的意思。在d.ts文件里面,在最外层声明变量或者函数或者类要在前面加上这个关键字。在typescript的规则里面,如果一个.ts.d.ts文件如果没有用到import或者export语法的话,那么最顶层声明的变量就是全局变量。

  • 函数

     由上面的全局变量的写法我们很自然的推断出一个全局函数的写法如下:

/** id是用户的id,可以是number或者string */
decalre function getName(id:number|string):string

最后的那个string表示的是函数的返回值的类型。如果函数没有返回值可以用void表示。

  • class

      当然除了变量和函数外,我们还有类(class)。

declare class Person {

    static maxAge: number //静态变量
    static getMaxAge(): number //静态方法

    constructor(name: string, age: number)  //构造函数
    getName(id: number): string 
}
    • constructor表示的是构造方法:
    • 其中static表示静态的意思,用来表示静态变量和静态方法:
  • 对象

declare namespace OOO{
    
}

当然了这个对象上面可能有变量,可能有函数可能有类。

declare namespace OOO{
    var aaa: number | string
    function getName(id: number | string): string
    class Person {

        static maxAge: number //静态变量
        static getMaxAge(): number //静态方法

        constructor(name: string, age: number) //构造函数
        getName(id: number): string //实例方法
    }
}

其实就是把上面的那些写法放到这个namespace包起来的大括号里面,注意括号里面就不需要declare关键字了。

对象里面套对象也是可以的:

declare namespace OOO{
    var aaa: number | string
    // ...
    namespace O2{
        let b:number
    }
}
  • 混合类型

   有时候有些值既是函数又是class又是对象的复杂对象。比如我们常用的jquery有各种用法:

new $()
$.ajax()
$()

    下面写声明一个  既是函数又是对象:

declare function $2(s:string): void

declare namespace $2{
    let aaa:number
}

二、ES6的模块化方式(import export)   【CommonJS模式这里不讲

  除了上面的全局的方式,我们有时候还是通过 import 的方式引入模块化的代码。

declare var aaa: 1
declare var bbb: 2
declare var ccc: 3 //因为这个文件里我们使用了import或者export语法,所以bbb和ccc在其他代码里不能访问到,即不是全局变量

export { aaa }

 使用:

import { a1, a2 } from "./A"

console.log(a1)
console.log(a2)