声明文件是Typescript学习中的一个难点,而网上的资料又少之又少。jQuery作为一个使用频率极高的库,学会它的声明文件的写法,则很容易做到触类旁通。

第一步.

对于$("#app")$(function(){})这种写法,$是作为一个函数存在的,因此声明文件写法如下:

1
2
3
4
5

//动态方法
declare function $(cb:Function):void

declare function $(selector:string):void

为了能够链式调用,添加$函数的返回值类型

1
2
3
4
5
6
7
8
9
10
//动态方法
declare function $(cb:Function):void

declare function $(selector:string):jQueryElement


interface jQueryElement{
html(content : string): jQueryElement
css(content : string) : jQueryElement
}

而对于是否$上的静态方法,如$.ajax, $ 是作为一个对象存在的,ajax是$对象上的一个属性,因此声明文件写法如下:

1
2
3
4
5
interface jQueryStatic{
ajax(option:object):void
}

declare let jQuery:jQueryStatic

第二步.

直接将第一步的写法放在一起会有冲突,因为重复定义了$; 所以采用下面的方法合并起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

interface jQueryElement{
html(content : string): jQueryElement
css(content : string) : jQueryElement
}

//静态方法
interface JQueryStatic {
ajax(options:object):void;
(cb:Function):jQueryElement //这儿只要区分类型,然后返回jQueryElement就可以了,而不是像jQueryElement中写出方法名字
(selector:string):jQueryElement
}

declare let jQuery:JQueryStatic
declare let $:JQueryStatic

这种写法就相当于函数加函数属性上的方法。