美文网首页
TypeScript(六) 类型别名/推论以及内置对象

TypeScript(六) 类型别名/推论以及内置对象

作者: 梦晓半夏_d68a | 来源:发表于2022-12-26 00:30 被阅读0次

类型别名

type Name = string;

类型推论

如果在声明变量时同时进行了初始化,则可以不用变量类型的申明。 实际上ts会根据类型推论(Type Inference)的规则推断出一个类型

// 以下两句等同
let name = 'tom'
let name:string = 'tom'

如果声明变量时没有进行初始化,都会被推断成 any 类型而完全不被类型检查,any类型已经详细写过,在此不再赘述。

内置对象

JavaScript 中有一些内置对象,在定义类型时可以直接使用。
ECMAScript 的内置对象
BooleanErrorDateRegExp 等。详见更多内置对象

我们可以在 TypeScript 中将变量定义为这些类型:

let b: Boolean = new Boolean(1);
let e: Error = new Error('Error occurred');
let d: Date = new Date();
let r: RegExp = /[a-z]/;

DOM 和 BOM 的内置对象

包括DocumentHTMLElementEventMouseEventNodeList 等。

TypeScript 中会经常用到这些类型:

let body: HTMLElement = document.body;
let allDiv: NodeList = document.querySelectorAll('div');
document.addEventListener('click', function(e: MouseEvent) {
  // Do something
});

定义文件详见 TypeScript 核心库的定义文件中。

TypeScript 核心库的定义文件

TypeScript 核心库的定义文件中定义了所有浏览器环境需要用到的类型,并且是预置在 TypeScript 中的。

当你在使用一些常用的方法的时候,TypeScript 实际上已经帮你做了很多类型判断的工作了,比如:

Math.pow(10, '2');

// 报错:Argument of type 'string' is not assignable to parameter of type 'number'

上面的例子中,Math.pow 必须接受两个 number 类型的参数。事实上 Math.pow 的类型定义如下:

interface Math {
    /**
     * Returns the value of a base expression taken to a specified power.
     * @param x The base value of the expression.
     * @param y The exponent value of the expression.
     */
    pow(x: number, y: number): number;
}

再举一个 DOM 中的例子:

document.addEventListener('click', function(e) {
    console.log(e.targetCurrent);
});

// Property 'targetCurrent' does not exist on type 'MouseEvent'.

上面的例子中,addEventListener 方法是在 TypeScript 核心库中定义的:

interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEvent {
    addEventListener(type: string, listener: (ev: MouseEvent) => any, useCapture?: boolean): void;
}

所以 e 被推断成了 MouseEvent,而 MouseEvent 是没有 targetCurrent 属性的,所以报错了。

注意,TypeScript 核心库的定义中不包含 Node.js 部分。

相关文章

网友评论

      本文标题:TypeScript(六) 类型别名/推论以及内置对象

      本文链接:https://www.haomeiwen.com/subject/exmiqdtx.html