在 Typescript 数组类型 这篇文章末咱们说起到了 Typescripe 一种内置对象。node
在 Typescript 中内置对象是做为已经定义好(内置)的类型去使用的,很显然它是存在全局做用域(Global)上。git
拿 Boolean
这个内置对象来讲吧,这样的对象在 ECMAScript 中有不少。github
// buildInObjects.ts
let b1: boolean = new Boolean(1);
let b2: Boolean = new Boolean(1);
// 0.0.7/buildInObjects.ts:1:5 - error TS2322: Type 'Boolean' is not assignable to type 'boolean'.
// 'boolean' is a primitive, but 'Boolean' is a wrapper object. Prefer using 'boolean' when possible.
// 1 let b1: boolean = new Boolean(1);
复制代码
第 1 行报错,咱们在 Typescript 基础类型 就分析过了,不能将 Boolean
分配给 boolean
,前者是包装器对象,后者是基本类型。这也间接说明第 2 行能正常运行的缘由了。typescript
// buildInObjects2.ts
const body: HTMLElement = document.body;
const divList: NodeList = document.querySelectorAll('div');
document.addEventListener('click', (e: MouseEvent) => {
// do something
});
复制代码
示例中 HTMLElement
、NodeList
和 MouseEvent
就是 DOM 与 BOM 内置对象。npm
总结:无论 ECMAScript 内置对象仍是 DOM 与 BOM 的内置对象,其文件定义在 TypeScript 核心库的文件 中。下面就说说它。数组
是否是也内置了呀?这个,这个不是了。你得引入第三方声明文件。这里牵扯到声明文件,下一篇内容咱们来讲说。浏览器
npm install @types/node --save-dev
复制代码
它定义了浏览器环境全部类型,预置在 Typescript 中,因此咱们能随手拿来用。而这些文件都帮咱们作了不少判断工做了(一个字省心)。bash
// buildInObjects3.ts
Math.pow(10, '3');
// 0.0.7/buildInObjects3.ts:1:14 - error TS2345: Argument of type '"3"' is not assignable to parameter of type 'number'.
// 1 Math.pow(10, '3');
复制代码
经过错误提示咱们能够推断出 Math.pow
是这么定义的app
// buildInObjects4.ts
interface Math {
pow(x:number, y:number): number;
join(x:string, y:string): string;
}
Math.join('1', '2');
Math.join('1', 2);
// 0.0.7/buildInObjects4.ts:7:16 - error TS2345: Argument of type '2' is not assignable to parameter of type 'string'.
// 7 Math.join('1', 2);
复制代码
在推断 Math.pow
类型定义的同时,顺便造了一个 Math.join
,其输入类型和输出类型都是字符串,随后调用这个方法时参数传了数字类型,于是同 Math.pow(10, '3')
错误相似。函数