- // $ 作为对象时
- declare namespace $ {
- function Ajax(url: string, settings:any):void;
- let name: string;
- namespace fn {
- function extend(object: any):void
- }
- }
- // 示例
- $.Ajax('./url', {})
- // $ 作为函数时
- declare function $(selector: string): htmlElement;
- // 示例
- $('#root')
2. 类型声明文件
类型声明的文件的后缀为 .d.ts.
对应的 tsconfig.JSON 中的相关配置参数有:
- include: [
- "./src/**/*" // 表示 ts 编译时针对 src 文件夹下的所有的. ts 后缀的文件,
- "./types/**/*"
- ]
如果不设置该属性, 则默认编译所有文件夹下的文件.
1. 自定义第三方类型声明文件
在引入文件定义查找路径的规则时, 需要在 tsconfig.JSON 中的 compilerOptions 中配置 paths+baseUrl.
- "baseUrl": "./", /* 解决相对路径; 设置 paths 时, 该属性必须存在 */
- "paths": {
- "*": ["types/*"]
- }, /* import 引入文件查找对应的声明文件时的相对于 baseUrl 的路径 */
- src/index.ts
- import * as jQuery from 'jquery';
- jQuery.default.Ajax('/users', {});
安装 jQuery
NPM install -S jQuery
自定义 jQuery 的声明文件: types/jQuery.d.ts
- declare function jQuery(params:string): HTMLElement;
- declare namespace jQuery {
- function Ajax(url: string, setting: any): void;
- }
- export default jQuery;
2. 第三方类型声明文件库
类型声明文件的查找优先级
根据配置文件的 paths 查找自定义的类型声明文件, 如果无, 向下
查找 node_modules/XXX/package.JSON 中 types 字段, 如果无, 向下
查找 node_modules/XXX/index.d.ts
查找 node_modules/@types/XXX/index.d.ts
对于常用的 JS 库的类型声明文件, 有现成的声明文件 @types/*.
示例:
1. 安装 @types/jQuery
2. 直接使用
??: 如果自定义的类型声明文件也存在时, 会使用自定义的类型声明文件
import * as jQuery from 'jquery';
jQuery.Ajax('./uers');
3. 类型声明扩展
本质上是扩展目标对象的属性值
1. 扩展全局变量 - declare global
当前文件中使用了 export 关键字, 为局部文件, 需要在该文件中扩展全局变量
export{};
declare global {
interface String {
double(): string;
}
interface Windows {
myname: string;
}
}
String.prototype.double = function(){
return this.toLowerCase() + this;
}
console.log('lee'.double());
Windows.myname = "hello world"
2. 使用命名空间扩展
使用命名空间扩展类
给类添加属性
class Form {
username: Form.Item = ""; //Form 在此处用作命名空间
password: Form.Item = "";
}
// 使用 declare 时, 内部不需要 export;
// declare 已经表明可以被外部使用
declare namespace Form {
class Item{}
}
// 或者
/*
namespace Form {
export class Item{}
}
*/
- let form: Form = {
- username: "",
- password: ""
- }
使用命名空间扩展函数
给函数添加属性
- declare function jQuery(selector: string): HTMLElement;
- declare namespace jQuery {
- let name: string;
- }
使用命名空间扩展枚举
扩展枚举值的选项
- enum Color {
- RED=1,
- BLUE
- }
- declare namespace Color {
- const GREEN = 3;
- const VIOLET = 4;
- }
- let color = Color.GREEN;
- console.log(color)
来源: http://www.bubuko.com/infodetail-3445817.html