We mentioned Typescripe as a built-in object at the end of the Typescript array types article.

Built-in objects in Typescript are used as defined (built-in) types, which obviously exist in the Global scope.

ECMAScript built-in objects

Take the Boolean built-in object, for example. There are many such objects in ECMAScript.

// 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);
Copy the code

In line 1, we examined Typescript primitives. Boolean cannot be assigned to Boolean, which is a wrapper object, and Boolean, which is a primitives type. This indirectly explains why line 2 works.

DOM and BOM built-in objects

// buildInObjects2.ts
const body: HTMLElement = document.body;
const divList: NodeList = document.querySelectorAll('div');
document.addEventListener('click'.(e: MouseEvent) = > {
    // do something
});
Copy the code

In the example HTMLElement, NodeList, and MouseEvent are DOM and BOM built-in objects.

Summary: Whether ECMAScript built-in objects or DOM and BOM built-in objects, their files are defined in the TypeScript core library files. So let’s talk about it.

Application in Node.js

Is it built in? This one, this one’s not. You have to bring in a third party declaration file. This is where the declaration file comes in. Let’s talk about it in the next article.

npm install @types/node --save-dev
Copy the code

Files for the TypeScript core library

It defines all the types of the browser environment, and it’s preset in Typescript so we can use it anywhere. And these documents help us do a lot of judgment work (save a word).

// buildInObjects3.ts
Math.pow(10.'3');

/ / 0.0.7 buildInObjects3. Ts: 1:14 - error TS2345: Argument of type '" 3 "is not assignable to the parameter of type' number '.
    // 1 Math.pow(10, '3');
Copy the code

We can infer from the error that math.pow is defined this way

// 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 the parameter of type "string".
    // 7 Math.join('1', 2);
Copy the code

While inferring the math. pow type definition, we build a Math.join whose input and output types are strings, and then call this method with numeric types as arguments, so it’s similar to the math. pow(10, ‘3’) error.

This code Github

You can…

Previous: Typescript function types

Next: Typescript primitives

Contents: A primer to Typescript’s short book