lib.d.ts 的内容主要是一些变量声明(如:windowdocumentmath)和一些类似的接口声明(如:WindowDocumentMath)。

当你安装 TypeScript 时,会顺带安装 lib.d.ts 等声明文件。此文件包含了 JavaScript 运行时以及 DOM 中存在各种常见的环境声明。这些文件安装在编辑器的资源列表中,在本地开发代码时,typescript实时编译,这些声明文件会自动包含在编译上下文中,智能提示也是靠这些文件实现的。

1.ECMAScript 的内置对象

  1. 1.Boolean
  2. let b: Boolean = new Boolean(1);
  3. 2.Error
  4. let e: Error = new Error('Error occurred')
  5. 3.Date
  6. let d: Date = new Date();
  7. 4.RegExp
  8. let r: RegExp = /[a-z]/;

2.DOM 和 BOM 的内置对象

  1. 1.HTMLElement
  2. let body: HTMLElement = document.body;
  3. 2.NodeList
  4. let allDiv: NodeList = document.querySelectorAll('div');
  5. 3.event
  6. document.addEventListener('click', function(e: MouseEvent) {
  7. // Do something
  8. });

3.TypeScript预置类型

TypeScript 核心库的定义文件中定义了所有浏览器环境需要用到的类型

  1. Math.pow(10, '2');
  2. // index.ts(1,14): error TS2345: Argument of type 'string' is not assignable to
  3. //parameter of type 'number'.
  4. //Math对象类型定义
  5. interface Math {
  6. /**
  7. * Returns the value of a base expression taken to a specified power.
  8. * @param x The base value of the expression.
  9. * @param y The exponent value of the expression.
  10. */
  11. pow(x: number, y: number): number;
  12. }

4.编译目标对 lib.d.ts 的影响

  • --target 选项为 es5 时,会导入 es5, dom, scripthost。
  • --target 选项为 es6 时,会导入 es6, dom, dom.iterable, scripthost。