TypeScript 是一种由微软开发的自由和开源的编程语言。它是 Javascript 的一个超集,而且本质上向这个语言添加了可选的静态类型和基于类的面向对象编程。
本文阿宝哥将分享这些年在学习 TypeScript 过程中,遇到的 10 大 “奇怪” 的符号。其中有一些符号,阿宝哥第一次见的时候也觉得 “一脸懵逼”,希望本文对学习 TypeScript 的小伙伴能有一些帮助。
好的,下面我们来开始介绍第一个符号 —— ! 非空断言操作符。
在上下文中当类型检查器无法断定类型时,一个新的后缀表达式操作符 !
可以用于断言操作对象是非 null 和非 undefined 类型。具体而言,x! 将从 x 值域中排除 null 和 undefined 。
那么非空断言操作符到底有什么用呢?下面我们先来看一下非空断言操作符的一些使用场景。
1.1 忽略 undefined 和 null 类型
function myFunc(maybeString: string | undefined | null) {// Type 'string | null | undefined' is not assignable to type 'string'.// Type 'undefined' is not assignable to type 'string'. const onlyString: string = maybeString; // Errorconst ignoreUndefinedAndNull: string = maybeString!; // Ok
}
1.2 调用函数时忽略 undefined 类型
type NumGenerator = () => number;function myFunc(numGenerator: NumGenerator | undefined) {// Object is possibly 'undefined'.(2532)// Cannot invoke an object which is possibly 'undefined'.(2722)const num1 = numGenerator(); // Errorconst num2 = numGenerator!(); //OK
}
因为 !
非空断言操作符会从编译生成的 Javascript 代码中移除,所以在实际使用的过程中,要特别注意。比如下面这个例子:
const a: number | undefined = undefined;
const b: number = a!;
console.log(b);
以上 TS 代码会编译生成以下 ES5 代码:
"use strict";
const a = undefined;
const b = a;
console.log(b);
虽然在 TS 代码中,我们使用了非空断言,使得 const b: number = a!;
语句可以通过 TypeScript 类型检查器的检查。但在生成的 ES5 代码中,!
非空断言操作符被移除了,所以在浏览器中执行以上代码,在控制台会输出 undefined
。
TypeScript 3.7 实现了呼声最高的 ECMAScript 功能之一:可选链(Optional Chaining)。有了可选链后,我们编写代码时如果遇到 null
或 undefined
就可以立即停止某些表达式的运行。可选链的核心是新的 ?.
运算符,它支持以下语法:
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)
这里我们来举一个可选的属性访问的例子:
const val = a?.b;
为了更好的理解可选链,我们来看一下该 const val = a?.b
语句编译生成的 ES5 代码:
var val = a === null || a === void 0 ? void 0 : a.b;
上述的代码会自动检查对象 a 是否为 null
或 undefined
,如果是的话就立即返回 undefined
,这样就可以立即停止某些表达式的运行。你可能已经想到可以使用 ?.
来替代很多使用 &&
执行空检查的代码:
if(a && a.b) { } if(a?.b){ }
/**
* if(a?.b){ } 编译后的ES5代码
*
* if(
* a === null || a === void 0
* ? void 0 : a.b) {
* }
*/
但需要注意的是,?.
与 &&
运算符行为略有不同,&&
专门用于检测 falsy
值,比如空字符串、0、NaN、null 和 false 等。而 ?.
只会验证对象是否为 null
或 undefined
,对于 0 或空字符串来说,并不会出现 “短路”。
2.1 可选元素访问
可选链除了支持可选属性的访问之外,它还支持可选元素的访问,它的行为类似于可选属性的访问,只是可选元素的访问允许我们访问非标识符的属性,比如任意字符串、数字索引和 Symbol:
function tryGetArrayElement 以上代码经过编译后会生成以下 ES5 代码&#xff1a; "use strict"; 通过观察生成的 ES5 代码&#xff0c;很明显在 2.2 可选链与函数调用 当尝试调用一个可能不存在的方法时也可以使用可选链。在实际开发过程中&#xff0c;这是很有用的。系统中某个方法不可用&#xff0c;有可能是由于版本不一致或者用户设备兼容性问题导致的。函数调用时如果被调用的方法不存在&#xff0c;使用可选链可以使表达式自动返回 可选调用使用起来也很简单&#xff0c;比如&#xff1a; let result &#61; obj.customMethod?.(); 该 TypeScript 代码编译生成的 ES5 代码如下&#xff1a; var result &#61; (_a &#61; obj.customMethod) &#61;&#61;&#61; null|| _a &#61;&#61;&#61; void 0 ? void 0 : _a.call(obj); 另外在使用可选调用的时候&#xff0c;我们要注意以下两个注意事项&#xff1a; 在 TypeScript 3.7 版本中除了引入了前面介绍的可选链 与逻辑或 这里来看一个具体的例子&#xff1a; const foo &#61; null ?? &#39;default string&#39;; 以上 TS 代码经过编译后&#xff0c;会生成以下 ES5 代码&#xff1a; "use strict"; 通过观察以上代码&#xff0c;我们更加直观的了解到&#xff0c;空值合并运算符是如何解决前面 3.1 短路 当空值合并运算符的左表达式不为 function A() { console.log(&#39;A was called&#39;); return undefined;} 上述代码运行后&#xff0c;控制台会输出以下结果&#xff1a; A was called 3.2 不能与 && 或 || 操作符共用 若空值合并运算符 // &#39;||&#39; and &#39;??&#39; operations cannot be mixed without parentheses.(5076) 但当使用括号来显式表明优先级时是可行的&#xff0c;比如&#xff1a; (null || undefined ) ?? "foo"; // 返回 "foo" 3.3 与可选链操作符 ?. 的关系 空值合并运算符针对 undefined 与 null 这两个值&#xff0c;可选链式操作符 interface Customer {name: string;city?: string; 前面我们已经介绍了空值合并运算符的应用场景和使用时的一些注意事项&#xff0c;该运算符不仅可以在 TypeScript 3.7 以上版本中使用。当然你也可以在 Javascript 的环境中使用它&#xff0c;但你需要借助 Babel&#xff0c;在 Babel 7.8.0 版本也开始支持空值合并运算符。 在面向对象语言中&#xff0c;接口是一个很重要的概念&#xff0c;它是对行为的抽象&#xff0c;而具体如何行动需要由类去实现。 TypeScript 中的接口是一个非常灵活的概念&#xff0c;除了可用于对类的一部分行为进行抽象以外&#xff0c;也常用于对「对象的形状&#xff08;Shape&#xff09;」进行描述。 在 TypeScript 中使用 interface Person {name: string;age: number; 在以上代码中&#xff0c;我们声明了 // Property &#39;age&#39; is missing in type &#39;{ name: string; }&#39; but required in type &#39;Person&#39;.(2741) 为了解决上述的问题&#xff0c;我们可以把某个属性声明为可选的&#xff1a; interface Person {name: string;age?: number; 4.1 工具类型 4.1.1 在实际项目开发过程中&#xff0c;为了提高代码复用率&#xff0c;我们可以利用 TypeScript 内置的工具类型 interface PullDownRefreshConfig {threshold: number;stop: number; 是不是觉得 /*** Make all properties in T optional*/ 4.1.2 既然可以快速地把某个接口中定义的属性全部声明为可选&#xff0c;那能不能把所有的可选的属性变成必选的呢&#xff1f;答案是可以的&#xff0c;针对这个需求&#xff0c;我们可以使用 interface PullDownRefreshConfig {threshold: number;stop: number; 同样&#xff0c;我们来看一下 /*** Make all properties in T required*/ 原来在 在 TypeScript 中交叉类型是将多个类型合并为一个类型。通过 type PartialPointX &#61; { x: number; }; 在上面代码中我们先定义了 5.1 同名基础类型属性的合并 那么现在问题来了&#xff0c;假设在合并多个类型的过程中&#xff0c;刚好出现某些类型存在相同的成员&#xff0c;但对应的类型又不一致&#xff0c;比如&#xff1a; interface X {c: string;d: string; 在上面的代码中&#xff0c;接口 X 和接口 Y 都含有一个相同的成员 c&#xff0c;但它们的类型不一致。对于这种情况&#xff0c;此时 XY 类型或 YX 类型中成员 c 的类型是不是可以是 p &#61; { c: 6, d: "d", e: "e" }; q &#61; { c: "c", d: "d", e: "e" }; 为什么接口 X 和接口 Y 混入后&#xff0c;成员 c 的类型会变成 5.2 同名非基础类型属性的合并 在上面示例中&#xff0c;刚好接口 X 和接口 Y 中内部成员 c 的类型都是基本数据类型&#xff0c;那么如果是非基本数据类型的话&#xff0c;又会是什么情形。我们来看个具体的例子&#xff1a; interface D { d: boolean; } 以上代码成功运行后&#xff0c;控制台会输出以下结果&#xff1a; 由上图可知&#xff0c;在混入多个类型时&#xff0c;若存在相同的成员&#xff0c;且成员类型为非基本数据类型&#xff0c;那么是可以成功合并。 在 TypeScript 中联合类型&#xff08;Union Types&#xff09;表示取值可以为多种类型中的一种&#xff0c;联合类型使用 const sayHello &#61; (name: string | undefined) &#61;> { /* ... */ }; 以上示例中 sayHello("semlinker"); 此外&#xff0c;对于联合类型来说&#xff0c;你可能会遇到以下的用法&#xff1a; let num: 1 | 2 &#61; 1; 示例中的 6.1 类型保护 当使用联合类型时&#xff0c;我们必须尽量把当前值的类型收窄为当前值的实际类型&#xff0c;而类型保护就是实现类型收窄的一种手段。 类型保护是可执行运行时检查的一种表达式&#xff0c;用于确保该类型在一定的范围内。换句话说&#xff0c;类型保护可以保证一个字符串是一个字符串&#xff0c;尽管它的值也可以是一个数字。类型保护与特性检测并不是完全不同&#xff0c;其主要思想是尝试检测属性、方法或原型&#xff0c;以确定如何处理值。 目前主要有四种的方式来实现类型保护&#xff1a; 6.1.1 in 关键字 interface Admin {name: string;privileges: string[]; 6.1.2 typeof 关键字 function padLeft(value: string, padding: string | number) {if (typeof padding &#61;&#61;&#61; "number") {return Array(padding &#43; 1).join(" ") &#43; value;}if (typeof padding &#61;&#61;&#61; "string") {return padding &#43; value;}throw new Error(&#96;Expected string or number, got &#39;${padding}&#39;.&#96;); 6.1.3 instanceof 关键字 interface Padder {getPaddingString(): string; 6.1.4 自定义类型保护的类型谓词&#xff08;type predicate&#xff09; function isNumber(x: any): x is number {return typeof x &#61;&#61;&#61; "number"; TypeScript 2.7 带来了对数字分隔符的支持&#xff0c;正如数值分隔符 ECMAScript 提案中所概述的那样。对于一个数字字面量&#xff0c;你现在可以通过把一个下划线作为它们之间的分隔符来分组数字&#xff1a; const inhabitantsOfMunich &#61; 1_464_301; 分隔符不会改变数值字面量的值&#xff0c;但逻辑分组使人们更容易一眼就能读懂数字。以上 TS 代码经过编译后&#xff0c;会生成以下 ES5 代码&#xff1a; "use strict"; 7.1 使用限制 虽然数字分隔符看起来很简单&#xff0c;但在使用时还是有一些限制。比如你只能在两个数字之间添加 // Numeric separators are not allowed here.(6188) 当然你也不能连续使用多个 // Multiple consecutive numeric separators are not permitted.(6189) 7.2 解析分隔符 此外&#xff0c;需要注意的是以下用于解析数字的函数是不支持分隔符&#xff1a; 这里我们来看一下实际的例子&#xff1a; Number(&#39;123_456&#39;) 很明显对于以上的结果不是我们所期望的&#xff0c;所以在处理分隔符时要特别注意。当然要解决上述问题&#xff0c;也很简单只需要非数字的字符删掉即可。这里我们来定义一个 const RE_NON_DIGIT &#61; /[^0-9]/gu;function removeNonDigits(str) {str &#61; str.replace(RE_NON_DIGIT, &#39;&#39;);return Number(str); 该函数通过调用字符串的 removeNonDigits(&#39;123_456&#39;) 8.1 TypeScript 断言 有时候你会遇到这样的情况&#xff0c;你会比 TypeScript 更了解某个值的详细信息。通常这会发生在你清楚地知道一个实体具有比它现有类型更确切的类型。 通过类型断言这种方式可以告诉编译器&#xff0c;“相信我&#xff0c;我知道自己在干什么”。类型断言好比其他语言里的类型转换&#xff0c;但是不进行特殊的数据检查和解构。它没有运行时的影响&#xff0c;只是在编译阶段起作用。 类型断言有两种形式&#xff1a; 8.1.1 “尖括号” 语法 let someValue: any &#61; "this is a string"; 8.1.2 as 语法 let someValue: any &#61; "this is a string"; 8.2 TypeScript 泛型 对于刚接触 TypeScript 泛型的读者来说&#xff0c;首次看到 参考上面的图片&#xff0c;当我们调用 其中 其实并不是只能定义一个类型变量&#xff0c;我们可以引入希望定义的任何数量的类型变量。比如我们引入一个新的类型变量 function identity 除了为类型变量显式设定值之外&#xff0c;一种更常见的做法是使编译器自动选择这些类型&#xff0c;从而使代码更简洁。我们可以完全省略尖括号&#xff0c;比如&#xff1a; function identity 对于上述代码&#xff0c;编译器足够聪明&#xff0c;能够知道我们的参数类型&#xff0c;并将它们赋值给 T 和 U&#xff0c;而不需要开发人员显式指定它们。 9.1 装饰器语法 对于一些刚接触 TypeScript 的小伙伴来说&#xff0c;在第一次看到 &#64;Plugin({pluginName: &#39;Device&#39;,plugin: &#39;cordova-plugin-device&#39;,pluginRef: &#39;device&#39;,repo: &#39;https://github.com/apache/cordova-plugin-device&#39;,platforms: [&#39;Android&#39;, &#39;Browser&#39;, &#39;iOS&#39;, &#39;macOS&#39;, &#39;Windows&#39;], 在以上代码中&#xff0c;我们通过装饰器来保存 ionic-native 插件的相关元信息&#xff0c;而 var __decorate &#61; (this && this.__decorate) || function (decorators, target, key, desc) {var c &#61; arguments.length, r &#61; c <3 ? target : desc &#61;&#61;&#61; null ? desc &#61; Object.getOwnPropertyDescriptor(target, key) : desc, d;if (typeof Reflect &#61;&#61;&#61; "object" && typeof Reflect.decorate &#61;&#61;&#61; "function") r &#61; Reflect.decorate(decorators, target, key, desc);else for (var i &#61; decorators.length - 1; i >&#61; 0; i--) if (d &#61; decorators[i]) r &#61; (c <3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;return c > 3 && r && Object.defineProperty(target, key, r), r; 通过生成的代码可知&#xff0c; 9.2 装饰器的分类 在 TypeScript 中装饰器分为类装饰器、属性装饰器、方法装饰器和参数装饰器四大类。 9.2.1 类装饰器 类装饰器声明&#xff1a; declare type ClassDecorator &#61; 类装饰器顾名思义&#xff0c;就是用来装饰类的。它接收一个参数&#xff1a; 看完第一眼后&#xff0c;是不是感觉都不好了。没事&#xff0c;我们马上来个例子&#xff1a; function Greeter(target: Function): void {target.prototype.greet &#61; function (): void {console.log("Hello Semlinker!");}; 上面的例子中&#xff0c;我们定义了 9.2.2 属性装饰器 属性装饰器声明&#xff1a; declare type PropertyDecorator &#61; (target:Object, propertyKey: string | symbol ) &#61;> void; 属性装饰器顾名思义&#xff0c;用来装饰类的属性。它接收两个参数&#xff1a; 趁热打铁&#xff0c;马上来个例子热热身&#xff1a; function logProperty(target: any, key: string) {delete target[key];const backingField &#61; "_" &#43; key;Object.defineProperty(target, backingField, {writable: true,enumerable: true,configurable: true});// property getterconst getter &#61; function (this: any) {const currVal &#61; this[backingField];console.log(&#96;Get: ${key} &#61;> ${currVal}&#96;);return currVal;};// property setterconst setter &#61; function (this: any, newVal: any) {console.log(&#96;Set: ${key} &#61;> ${newVal}&#96;);this[backingField] &#61; newVal;};// Create new property with getter and setterObject.defineProperty(target, key, {get: getter,set: setter,enumerable: true,configurable: true}); 以上代码我们定义了一个 Set: name &#61;> semlinker 9.2.3 方法装饰器 方法装饰器声明&#xff1a; declare type MethodDecorator &#61; 方法装饰器顾名思义&#xff0c;用来装饰类的方法。它接收三个参数&#xff1a; 废话不多说&#xff0c;直接上例子&#xff1a; function LogOutput(tarage: Function, key: string, descriptor: any) {let originalMethod &#61; descriptor.value;let newMethod &#61; function(...args: any[]): any {let result: any &#61; originalMethod.apply(this, args);if(!this.loggedOutput) {this.loggedOutput &#61; new Array 9.2.4 参数装饰器 参数装饰器声明&#xff1a; declare type ParameterDecorator &#61; (target: Object, propertyKey: string | symbol, parameterIndex: number ) &#61;> void 参数装饰器顾名思义&#xff0c;是用来装饰函数参数&#xff0c;它接收三个参数&#xff1a; function Log(target: Function, key: string, parameterIndex: number) {let functionLogged &#61; key || target.prototype.constructor.name;console.log(&#96;The parameter in position ${parameterIndex} at ${functionLogged} hasbeen decorated&#96;); 在 TypeScript 3.8 版本就开始支持 ECMAScript 私有字段&#xff0c;使用方式如下&#xff1a; class Person {#name: string;constructor(name: string) {this.#name &#61; name;}greet() {console.log(&#96;Hello, my name is ${this.#name}!&#96;);} 与常规属性&#xff08;甚至使用 10.1 私有字段与 private 的区别 说到这里使用 class Person {constructor(private name: string){} 在上面代码中&#xff0c;我们创建了一个 Person 类&#xff0c;该类中使用 Property &#39;name&#39; is private and only accessible within class &#39;Person&#39;.(2341) 那如何解决这个异常呢&#xff1f;当然你可以使用类型断言把 person 转为 any 类型&#xff1a; console.log((person as any).name); 通过这种方式虽然解决了 TypeScript 编译器的异常提示&#xff0c;但是在运行时我们还是可以访问到 var Person &#61; /** &#64;class */ (function () {function Person(name) {this.name &#61; name;}return Person; 这时相信有些小伙伴会好奇&#xff0c;在 TypeScript 3.8 以上版本通过 class Person {#name: string;constructor(name: string) {this.#name &#61; name;}greet() {console.log(&#96;Hello, my name is ${this.#name}!&#96;);} 以上代码目标设置为 ES2015&#xff0c;会编译生成以下代码&#xff1a; "use strict"; 通过观察上述代码&#xff0c;使用
}
function tryGetArrayElement(arr, index) {if (index &#61;&#61;&#61; void 0) { index &#61; 0; }return arr &#61;&#61;&#61; null || arr &#61;&#61;&#61; void 0 ? void 0 : arr[index];
} tryGetArrayElement
方法中会自动检测输入参数 arr 的值是否为 null
或 undefined
&#xff0c;从而保证了我们代码的健壮性。undefined
而不是抛出一个异常。?.
仍然会产生一个 TypeError
异常。a?.b / someMethod()
表达式中的除法运算或 someMethod
的方法调用。三、?? 空值合并运算符
?.
之外&#xff0c;也引入了一个新的逻辑运算符 —— 空值合并运算符 ??
。当左侧操作数为 null 或 undefined 时&#xff0c;其返回右侧的操作数&#xff0c;否则返回左侧的操作数。||
运算符不同&#xff0c;逻辑或会在左操作数为 falsy 值时返回右侧操作数。也就是说&#xff0c;如果你使用 || 来为某些变量设置默认的值时&#xff0c;你可能会遇到意料之外的行为。比如为 falsy 值&#xff08;&#39;&#39;、NaN 或 0&#xff09;时。
console.log(foo); // 输出&#xff1a;"default string"const baz &#61; 0 ?? 42;
console.log(baz); // 输出&#xff1a;0
var _a, _b;
var foo &#61; (_a &#61; null) !&#61;&#61; null && _a !&#61;&#61; void 0 ? _a : &#39;default string&#39;;
console.log(foo); // 输出&#xff1a;"default string"var baz &#61; (_b &#61; 0) !&#61;&#61; null && _b !&#61;&#61; void 0 ? _b : 42;
console.log(baz); // 输出&#xff1a;0 ||
运算符存在的潜在问题。下面我们来介绍空值合并运算符的特性和使用时的一些注意事项。null
或 undefined
时&#xff0c;不会对右表达式进行求值。
function B() { console.log(&#39;B was called&#39;); return false;}
function C() { console.log(&#39;C was called&#39;); return "foo";}console.log(A() ?? C());
console.log(B() ?? C());
C was called
foo
B was called
false ??
直接与 AND&#xff08;&&&#xff09;和 OR&#xff08;||&#xff09;操作符组合使用 ?? 是不行的。这种情况下会抛出 SyntaxError。
null || undefined ?? "foo"; // raises a SyntaxError// &#39;&&&#39; and &#39;??&#39; operations cannot be mixed without parentheses.(5076)
true && undefined ?? "foo"; // raises a SyntaxError ?.
也是如此。可选链式操作符&#xff0c;对于访问属性可能为 undefined 与 null 的对象时非常有用。
}let customer: Customer &#61; {name: "Semlinker"
};let customerCity &#61; customer?.city ?? "Unknown city";
console.log(customerCity); // 输出&#xff1a;Unknown city 四、?: 可选属性
interface
关键字就可以声明一个接口&#xff1a;
}let semlinker: Person &#61; {name: "semlinker",age: 33,
}; Person
接口&#xff0c;它包含了两个必填的属性 name
和 age
。在初始化 Person 类型变量时&#xff0c;如果缺少某个属性&#xff0c;TypeScript 编译器就会提示相应的错误信息&#xff0c;比如&#xff1a;
let lolo: Person &#61; { // Errorname: "lolo"
}
}let lolo: Person &#61; {name: "lolo"
} Partial
Partial
来快速把某个接口类型中定义的属性变成可选的&#xff1a;
}/*** type PullDownRefreshOptions &#61; {* threshold?: number | undefined;* stop?: number | undefined;* }*/
type PullDownRefreshOptions &#61; PartialPartial
很方便&#xff0c;下面让我们来看一下它是如何实现的&#xff1a;
type Partial
}; Required
Required
工具类型&#xff0c;具体的使用方式如下&#xff1a;
}type PullDownRefreshOptions &#61; Partial
type PullDownRefresh &#61; RequiredRequired
工具类型是如何实现的&#xff1a;
type Required
}; Required
工具类型内部&#xff0c;通过 -?
移除了可选属性中的 ?
&#xff0c;使得属性从可选变为必选的。五、& 运算符
&
运算符可以将现有的多种类型叠加到一起成为一种类型&#xff0c;它包含了所需的所有类型的特性。
type Point &#61; PartialPointX & { y: number; };let point: Point &#61; {x: 1,y: 1
} PartialPointX
类型&#xff0c;接着使用 &
运算符创建一个新的 Point
类型&#xff0c;表示一个含有 x 和 y 坐标的点&#xff0c;然后定义了一个 Point
类型的变量并初始化。
}interface Y {c: number;e: string
}type XY &#61; X & Y;
type YX &#61; Y & X;let p: XY;
let q: YX; string
或 number
类型呢&#xff1f;比如下面的例子&#xff1a;never
呢&#xff1f;这是因为混入后成员 c 的类型为 string & number
&#xff0c;即成员 c 的类型既可以是 string
类型又可以是 number
类型。很明显这种类型是不存在的&#xff0c;所以混入后成员 c 的类型为 never
。
interface E { e: string; }
interface F { f: number; }interface A { x: D; }
interface B { x: E; }
interface C { x: F; }type ABC &#61; A & B & C;let abc: ABC &#61; {x: {d: true,e: &#39;semlinker&#39;,f: 666}
};console.log(&#39;abc:&#39;, abc); 六、| 分隔符
|
分隔每个类型。联合类型通常与 null
或 undefined
一起使用&#xff1a;name
的类型是 string | undefined
意味着可以将 string
或 undefined
的值传递给 sayHello
函数。
sayHello(undefined);
type EventNames &#61; &#39;click&#39; | &#39;scroll&#39; | &#39;mousemove&#39;; 1
、2
或 &#39;click&#39;
被称为字面量类型&#xff0c;用来约束取值只能是某几个值中的一个。
}interface Employee {name: string;startDate: Date;
}type UnknownEmployee &#61; Employee | Admin;function printEmployeeInformation(emp: UnknownEmployee) {console.log("Name: " &#43; emp.name);if ("privileges" in emp) {console.log("Privileges: " &#43; emp.privileges);}if ("startDate" in emp) {console.log("Start Date: " &#43; emp.startDate);}
}
} typeof
类型保护只支持两种形式&#xff1a;typeof v &#61;&#61;&#61; "typename"
和 typeof v !&#61;&#61; typename
&#xff0c;"typename"
必须是 "number"
&#xff0c; "string"
&#xff0c; "boolean"
或 "symbol"
。 但是 TypeScript 并不会阻止你与其它字符串比较&#xff0c;语言不会把那些表达式识别为类型保护。
}class SpaceRepeatingPadder implements Padder {constructor(private numSpaces: number) {}getPaddingString() {return Array(this.numSpaces &#43; 1).join(" ");}
}class StringPadder implements Padder {constructor(private value: string) {}getPaddingString() {return this.value;}
}let padder: Padder &#61; new SpaceRepeatingPadder(6);if (padder instanceof SpaceRepeatingPadder) {// padder的类型收窄为 &#39;SpaceRepeatingPadder&#39;
}
}function isString(x: any): x is string {return typeof x &#61;&#61;&#61; "string";
} 七、_ 数字分隔符
const distanceEarthSunInKm &#61; 149_600_000;
const fileSystemPermission &#61; 0b111_111_000;
const bytes &#61; 0b1111_10101011_11110000_00001101;
var inhabitantsOfMunich &#61; 1464301;
var distanceEarthSunInKm &#61; 149600000;
var fileSystemPermission &#61; 504;
var bytes &#61; 262926349; _
分隔符。以下的使用方式是非法的&#xff1a;
3_.141592 // Error
3._141592 // Error// Numeric separators are not allowed here.(6188)
1_e10 // Error
1e_10 // Error// Cannot find name &#39;_126301&#39;.(2304)
_126301 // Error
// Numeric separators are not allowed here.(6188)
126301_ // Error// Cannot find name &#39;b111111000&#39;.(2304)
// An identifier or keyword cannot immediately follow a numeric literal.(1351)
0_b111111000 // Error// Numeric separators are not allowed here.(6188)
0b_111111000 // Error _
分隔符&#xff0c;比如&#xff1a;
123__456 // Error Number()
parseInt()
parseFloat()
NaN
parseInt(&#39;123_456&#39;)
123
parseFloat(&#39;123_456&#39;)
123 removeNonDigits
的函数&#xff1a;
} replace
方法来移除非数字的字符&#xff0c;具体的使用方式如下&#xff1a;
123456
removeNonDigits(&#39;149,600,000&#39;)
149600000
removeNonDigits(&#39;1,407,836&#39;)
1407836 八、
语法
let strLength: number &#61; (
let strLength: number &#61; (someValue as string).length;
语法会感到陌生。其实它没有什么特别&#xff0c;就像传递参数一样&#xff0c;我们传递了我们想要用于特定函数调用的类型。identity
&#xff0c;Number
类型就像参数 1
一样&#xff0c;它将在出现 T
的任何位置填充该类型。图中
内部的 T
被称为类型变量&#xff0c;它是我们希望传递给 identity 函数的类型占位符&#xff0c;同时它被分配给 value
参数用来代替它的类型&#xff1a;此时 T
充当的是类型&#xff0c;而不是特定的 Number 类型。T
代表 Type&#xff0c;在定义泛型时通常用作第一个类型变量名称。但实际上 T
可以用任何有效名称代替。除了 T
之外&#xff0c;以下是常见泛型变量代表的意思&#xff1a;U
&#xff0c;用于扩展我们定义的 identity
函数&#xff1a;
}console.log(identity
}console.log(identity(68, "Semlinker")); 九、&#64;XXX 装饰器
&#64;Plugin({...})
这种语法可能会觉得很惊讶。其实这是装饰器的语法&#xff0c;装饰器的本质是一个函数&#xff0c;通过装饰器我们可以方便地定义与对象相关的元数据。
})
&#64;Injectable()
export class Device extends IonicNativePlugin {} &#64;Plugin({...})
中的 &#64;
符号只是语法糖&#xff0c;为什么说是语法糖呢&#xff1f;这里我们来看一下编译生成的 ES5 代码&#xff1a;
};var Device &#61; /** &#64;class */ (function (_super) {__extends(Device, _super);function Device() {return _super !&#61;&#61; null && _super.apply(this, arguments) || this;}Device &#61; __decorate([Plugin({pluginName: &#39;Device&#39;,plugin: &#39;cordova-plugin-device&#39;,pluginRef: &#39;device&#39;,repo: &#39;https://github.com/apache/cordova-plugin-device&#39;,platforms: [&#39;Android&#39;, &#39;Browser&#39;, &#39;iOS&#39;, &#39;macOS&#39;, &#39;Windows&#39;],}),Injectable()], Device);return Device;
}(IonicNativePlugin)); &#64;Plugin({...})
和 &#64;Injectable()
最终会被转换成普通的方法调用&#xff0c;它们的调用结果最终会以数组的形式作为参数传递给 __decorate
函数&#xff0c;而在 __decorate
函数内部会以 Device
类作为参数调用各自的类型装饰器&#xff0c;从而扩展对应的功能。
) &#61;> TFunction | void;
}&#64;Greeter
class Greeting {constructor() {// 内部实现}
}let myGreeting &#61; new Greeting();
myGreeting.greet(); // console output: &#39;Hello Semlinker!&#39;; Greeter
类装饰器&#xff0c;同时我们使用了 &#64;Greeter
语法糖&#xff0c;来使用装饰器。友情提示&#xff1a;读者可以直接复制上面的代码&#xff0c;在 TypeScript Playground 中运行查看结果。
}class Person { &#64;logPropertypublic name: string;constructor(name : string) { this.name &#61; name;}
}const p1 &#61; new Person("semlinker");
p1.name &#61; "kakuqo"; logProperty
函数&#xff0c;来跟踪用户对属性的操作&#xff0c;当代码成功运行后&#xff0c;在控制台会输出以下结果&#xff1a;
Set: name &#61;> kakuqo
}class Calculator {&#64;LogOutputdouble (num: number): number {return num * 2;}
}let calc &#61; new Calculator();
calc.double(11);
// console ouput: [{method: "double", output: 22, ...}]
console.log(calc.loggedOutput);
}class Greeter {greeting: string;constructor(&#64;Log phrase: string) {this.greeting &#61; phrase; }
}// console output: The parameter in position 0
// at Greeter has been decorated 十、#XXX 私有字段
}let semlinker &#61; new Person("Semlinker");semlinker.#name;
// ~~~~~
// Property &#39;#name&#39; is not accessible outside class &#39;Person&#39;
// because it has a private identifier. private
修饰符声明的属性&#xff09;不同&#xff0c;私有字段要牢记以下规则&#xff1a;#
字符开头&#xff0c;有时我们称之为私有名称&#xff1b;#
定义的私有字段与 private
修饰符定义字段有什么区别呢&#xff1f;现在我们先来看一个 private
的示例&#xff1a;
}let person &#61; new Person("Semlinker");
console.log(person.name); private
修饰符定义了一个私有属性 name
&#xff0c;接着使用该类创建一个 person
对象&#xff0c;然后通过 person.name
来访问 person
对象的私有属性&#xff0c;这时 TypeScript 编译器会提示以下异常&#xff1a;Person
类内部的私有属性&#xff0c;为什么会这样呢&#xff1f;我们来看一下编译生成的 ES5 代码&#xff0c;也许你就知道答案了&#xff1a;
}());var person &#61; new Person("Semlinker");
console.log(person.name); #
号定义的私有字段编译后会生成什么代码&#xff1a;
}
var __classPrivateFieldSet &#61; (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {if (!privateMap.has(receiver)) {throw new TypeError("attempted to set private field on non-instance");}privateMap.set(receiver, value);return value;
};var __classPrivateFieldGet &#61; (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {if (!privateMap.has(receiver)) {throw new TypeError("attempted to get private field on non-instance");}return privateMap.get(receiver);
};var _name;
class Person {constructor(name) {_name.set(this, void 0);__classPrivateFieldSet(this, _name, name);}greet() {console.log(&#96;Hello, my name is ${__classPrivateFieldGet(this, _name)}!&#96;);}
}
_name &#61; new WeakMap(); #
号定义的 ECMAScript 私有字段&#xff0c;会通过 WeakMap
对象来存储&#xff0c;同时编译器会生成 __classPrivateFieldSet
和 __classPrivateFieldGet
这两个方法用于设置值和获取值。