上节课我们讲了全局变量Window的扩展, 这节课我们再多讲几个技巧 .比如给”String”增加cut方法.
String.prototype.cut = function(n){return this.substr(0,n);};'12345'.cut(3); // 123
对应的声明文件:
// global.d.tsinterface String {// 自定义字段cut(s:string): string;}
因为”String”类型是ts系统自带的声明文件中写好的, 本身就是用interface描述的, 还记得interface类型会自动合并的特性吧, 这里直接写一个同名interface实现类型合并.
[
](https://github.com/microsoft/TypeScript/blob/main/lib/lib.es5.d.ts#L394)
系统的声明文件
js的api在ts中都是有类型声明的, 我们可以在项目的”node_modules/typescript/lib/“中看到所有的系统声明文件.
也可以在github上查看
带浏览器前缀的API
我观察发现系统自带的声明, 不会对带”浏览器前缀”的API进行声明, 如果我们自己写插件就需要补充这部分, 比如”requestFullScreen”这个api:
// global.d.ts
interface HTMLElement {
webkitRequestFullscreen(options?: FullscreenOptions): Promise<void>;
webkitRequestFullScreen(options?: FullscreenOptions): Promise<void>;
msRequestFullscreen(options?: FullscreenOptions): Promise<void>;
mozRequestFullScreen(options?: FullscreenOptions): Promise<void>;
}
源码: https://github.com/any86/be-full/blob/master/global.d.ts
