Typescript学习(一)
以下内容基于对TypeScript Deep Dive的学习。
目录
为什么使用TypeScript
为JavaScript提供可选类型系统
类型可以提高重构时的开发速度。通过有类型,在写代码的时候可以注意到错误,立即修复错误。
默认设置下,编译时即使有类型错误也会生成JavaScript代码。
将JavaScript未来版本中计划的功能用于当前(非现代)JavaScript环境
TypeScript使旧的JavaScript(ES5之前)运行环境也能使用ES6以后版本中计划的很多功能。TypeScript团队正在积极添加功能。
隐式推断类型
-
var foo = 123; // 推断为number类型
-
foo = '456'; // 错误: 无法将'string'代入'number'
明确指定类型
-
var foo: number = 123;
-
var foo: number = '123'; // 错误: 无法将'string'代入'number'
结构类型
-
interface Point2D {
-
x: number;
-
y: number;
-
}
-
interface Point3D {
-
x: number;
-
y: number;
-
z: number;
-
}
-
var point2D: Point2D = { x: 0, y: 10 }
-
var point3D: Point3D = { x: 0, y: 10, z: 20 }
-
function iTakePoint2D(point: Point2D) { /* 其他处理 */ }
-
-
iTakePoint2D(point2D); // 相同结构没问题
-
iTakePoint2D(point3D); // 多了属性也没问题
-
iTakePoint2D({ x: 0 }); // 错误:'y'不存在
使用既存JavaScript库的时候,可以使用declare声明消除编译时类型错误
-
$('.awesome').show(); // 错误:'$'不存在
-
-
declare var $: any;
-
$('.awesome').show(); // 不报错了
-
-
declare var $: { (selector: string): any };
-
$('.awesome').show(); // 不报错了
-
$(123).show(); // 错误: selector必须是string类型
代码风格
变量名、函数名、类成员和方法名、接口成员名、类型成员名 都使用小驼峰命名法,比如:camelCase
类名、接口名、类型名、命名空间、枚举类型和成员名 都使用大驼峰命名法,比如:PascalCase
接口名不加'I'前缀
null vs. undefined
推荐别使用null和undefined来声明不可用
-
// Bad
-
let foo = { x: 123, y: undefined };
-
// Good
-
let foo: { x: number, y?: number } = { x: 123 };
通常使用undefined
-
// Bad
-
return null;
-
// Good
-
return undefined;
如果是API或传统API的一部分,则使用null
-
// Bad
-
cb(undefined)
-
// Good
-
cb(null)
使用truthy检查对象是null或undefined
-
// Bad
-
if (error === null)
-
// Good
-
if (error)
使用== null / != null (不使用 === / !==)来检查null/undefined,因为同时适用于null和undefined,但不适用与其他假值(如:'',0,false)
-
// Bad
-
if (error !== null) // 只排除null,不排除undefined
-
// Good
-
if (error != null) // 同时排除null和undefined
使用代码格式化
引号
除非需要转义,否则建议使用单引号(')
如果不能使用双引号,请尝试使用反引号(`)
缩进使用2空格,不是TAB
语句后使用分号
声明数组使用foos: Foo[]而不使用foos: Array<Foo>
文件名使用小驼峰命名,比如:accordion.tsx、myControl.tsx、utils.ts
type vs interface
需要UNION型或交叉型时使用type
type Foo = number | { someProperty: number }
想做extend和implements的时候使用interface
-
interface Foo {
-
foo: string;
-
}
-
interface FooBar extends Foo {
-
bar: string;
-
}
-
class X implements FooBar {
-
foo: string;
-
bar: string;
-
}
== or ===
这两个都对TypeScript用户来说几乎是安全的。推荐使用TypeScript代码库中使用的===
JavaScript
判断相等
JavaScript需要注意的一点是==和===的不同,==会尝试在两个变量之间进行类型强制转换。
例如在以下情况下,字符串将转换为数字。
-
console.log(5 == "5"); // JavaScript:true , TypeScript会报错
-
console.log(5 === "5"); // JavaScript:false , TypeScript会报错
-
console.log("" == "0"); // JavaScript:false , TypeScript:false
-
console.log(0 == ""); // JavaScript:true , TypeScript会报错
与==和===一样,!=和!==会做同样的处理
所以,除了检查null以外,都建议使用===和!==
不能用于比较结构类型的内容
-
console.log({a:123} == {a:123}); // False
-
console.log({a:123} === {a:123}); // False
可以使用deep-equal npm包进行结构类型的比较
-
import * as deepEqual from "deep-equal";
-
console.log(deepEqual({a:123},{a:123})); // True
引用
除了文字(字符串、数字、boolean等)之外,JavaScript中的任何对象(包括函数、数组、正则表达式等)都是引用。
修改会影响所有引用的值
-
var foo = {};
-
var bar = foo; // bar是同一个对象的引用
-
foo.baz = 123;
-
console.log(bar.baz); // 123
等号比较也是比较的引用
-
var foo = {};
-
var bar = foo; // bar是foo的引用
-
var baz = {}; // baz是另一个对象
-
console.log(foo === bar); // true
-
console.log(foo === baz); // false
Null vs. Undefined
JavaScript(以及扩展的TypeScript)有两种底层类型:null和undefined。它们的意思是不同的:
内容尚未初始化:undefined
内容当前不可用:null
判断
-
console.log(undefined == undefined); // true
-
console.log(null == undefined); // true
-
console.log(0 == undefined); // false
-
console.log('' == undefined); // false
-
console.log(false == undefined); // false
推荐使用== null / != null (不使用 === / !==)来检查null/undefined,因为同时适用于null和undefined,但不适用与其他假值(如:'',0,false)
一般情况下不需要区分是null还是undefined
全局级别变量未定义的判断
-
if (typeof someglobal !== 'undefined') {
-
console.log(someglobal);
-
}
限制显式使用undefined
{a:1,b:undefined} 应该改成 {a:1}
Node形式的回调
Node形式的回调函数里,没有发生错误的时候,err对象一般设定为null,开发者使用truthy检查
-
fs.readFile('someFile', 'utf8', (err,data) => {
-
if (err) {
-
// 错误处理
-
} else {
-
// 正常处理
-
}
-
});
在创建自己的API时,为了保持一致性,在这种情况下可以使用null。
出于对自己API的诚意,您应该考虑promise,在这种情况下,您实际上不需要为缺少的错误值而烦恼(您使用.then与.catch来处理它们)。
不要使用undefined表示无效值
-
// Bad
-
function toInt(str:string) {
-
return str ? parseInt(str) : undefined;
-
}
-
// Good
-
function toInt(str: string): { valid: boolean, int?: number } {
-
const int = parseInt(str);
-
if (isNaN(int)) {
-
return { valid: false };
-
}
-
else {
-
return { valid: true, int };
-
}
-
}
JSON和序列化
JSON标准支持null的编码,不支持undefined
JSON.stringify({willStay: null, willBeGone: undefined}); // {"willStay":null}
this
函数中对this的访问取决于函数是如何调用的。这通常被称为调用上下文。
-
function foo() {
-
console.log(this);
-
}
-
foo(); // 全局调用,日志输出为window对象
-
let bar = {
-
foo
-
}
-
bar.foo(); // 在bar上调用,日志输出为bar对象
闭包(Closure)
JavaScript中的函数可以访问外部范围中定义的任何变量。
-
function outerFunction(arg) {
-
var variableInOuterFunction = arg;
-
function bar() {
-
console.log(variableInOuterFunction); // 访问外部范围中定义的变量
-
}
-
// 调用本地函数以证明它可以访问arg
-
bar();
-
}
-
outerFunction("hello closure"); // 日志输出:"hello closure"
即使在外部函数返回之后,内部函数也可以从外部范围访问变量。这是因为变量仍然绑定在内部函数中,而不依赖于外部函数。
-
function outerFunction(arg) {
-
var variableInOuterFunction = arg;
-
return function() {
-
console.log(variableInOuterFunction);
-
}
-
}
-
var innerFunction = outerFunction("hello closure!");
-
// 注意outerFunction已经返回
-
innerFunction(); // 日志输出:"hello closure!"
它允许轻松地组合对象,例如揭示模块模式(Revealing module pattern):
-
function createCounter() {
-
let val = 0;
-
return {
-
increment() { val },
-
getVal() { return val }
-
}
-
}
-
let counter = createCounter();
-
counter.increment();
-
console.log(counter.getVal()); // 1
-
counter.increment();
-
console.log(counter.getVal()); // 2
Number类型
核心类型
JavaScript只有一种数字类型。它是一个双精度64位数字。
10进制数(Decimal)
如果你是精通其他语言中double/float的人,你会知道二进制浮点与十进制小数对应不正确。
console.log(.1 .2); // 0.30000000000000004
整数(Integer)
整数值的界限是由内置的Number.MAX_SAFE_INTEGER和Number.MIN_SAFE_INTEGER决定。
-
console.log({max: Number.MAX_SAFE_INTEGER, min: Number.MIN_SAFE_INTEGER});
-
// {max: 9007199254740991, min: -9007199254740991}
在这种情况下,安全是指该值不能是舍入误差的结果。
不安全的值与这些安全值相差 1/-1,任何数量的加法/减法都将使结果舍入。
-
console.log(Number.MAX_SAFE_INTEGER 1 === Number.MAX_SAFE_INTEGER 2); // true!
-
console.log(Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2); // true!
-
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
-
console.log(Number.MAX_SAFE_INTEGER 1); // 9007199254740992 - Correct
-
console.log(Number.MAX_SAFE_INTEGER 2); // 9007199254740992 - Rounded!
-
console.log(Number.MAX_SAFE_INTEGER 3); // 9007199254740994 - Rounded - correct by luck
-
console.log(Number.MAX_SAFE_INTEGER 4); // 9007199254740996 - Rounded!
要检查安全性,请使用ES6的Number.isSafeInteger:
-
console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER)); // true
-
console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER 1)); // false
-
console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER 10)); // false
big.js
财务计算(例如GST计算、带美分的货币、加法等)时,都要使用big.js这样的库
完美十进制数学
安全的越界整数值
-
npm install big.js /big.js
-
-
import { Big } from 'big.js';
-
export const foo = new Big('111.11111111111111111111');
-
export const bar = foo.plus(new Big('0.00000000000000000001'));
-
// 获取数字
-
const x: number = Number(bar.toString()); // 失去精度
NaN
如果数字计算不能用有效数字表示,JavaScript将返回一个特殊的NaN值。
console.log(Math.sqrt(-1)); // NaN
不能用等号判断NaN,需要使用Number.isNaN
-
// Bad
-
console.log(NaN === NaN); // false!!
-
// Good
-
console.log(Number.isNaN(NaN)); // true
无穷大(Infinity)
Number可以表示的界限值为Number.MAX_VALUE和-Number.MAX_VALUE
-
console.log(Number.MAX_VALUE); // 1.7976931348623157e 308
-
console.log(-Number.MAX_VALUE); // -1.7976931348623157e 308
精度未更改的超出范围的值受这些限制。
-
console.log(Number.MAX_VALUE 1 == Number.MAX_VALUE); // true!
-
console.log(-Number.MAX_VALUE - 1 == -Number.MAX_VALUE); // true!
精度更改范围之外的值将解析为特殊值Infinity/-Infinity。
-
console.log(Number.MAX_VALUE 10**1000); // Infinity
-
console.log(-Number.MAX_VALUE - 10**1000); // -Infinity
除以0也是无穷大
-
console.log( 1 / 0); // Infinity
-
console.log(-1 / 0); // -Infinity
可以手动使用这些Infinity值,也可以使用Number类的静态成员
-
console.log(Number.POSITIVE_INFINITY === Infinity); // true
-
console.log(Number.NEGATIVE_INFINITY === -Infinity); // true
幸运的是,比较运算符(</>)可以起作用
-
console.log( Infinity > 1); // true
-
console.log(-Infinity < -1); // true
无穷小(Infinitesimal)
Number可以表示的非0最小值为Number.MIN_VALUE
console.log(Number.MIN_VALUE); // 5e-324
小于Number.MIN_VALUE的值就直接变0了
console.log(Number.MIN_VALUE / 10); // 0
Truthy
真假判断
变量类型 | 判定为False的值 | 判定为True的值 |
---|---|---|
boolean | false | true |
string | ''(空字符串) | 其他字符串 |
number | 0/NaN | 其他数字 |
null | 一直是false | |
undefined | 一直是false | |
其他对象(包含{}[]) | 一直是true |
使用!!可以强制转换成boolean类型,原理是两次取非运算
-
let name = 'abc';
-
const hasName = !!name; // hasName的值为true
现在使用未来JavaScript的功能
TypeScript的主要卖点之一是,它允许您在当前的(ES3和ES5级别)JavaScript引擎(如当前的浏览器和Node.js)中使用ES6及更高版本的一系列功能。
类
使用类
类提供了一个有用的结构抽象
为开发人员提供了一种一致的方式来使用类,而不是使用每个框架(emberjs、reactjs等)来开发自己的版本。
面向对象开发人员已经了解了类。
-
class Point {
-
x: number;
-
y: number;
-
constructor(x: number, y: number) {
-
this.x = x;
-
this.y = y;
-
}
-
add(point: Point) {
-
return new Point(this.x point.x, this.y point.y);
-
}
-
}
-
var p1 = new Point(0, 10);
-
var p2 = new Point(10, 20);
-
var p3 = p1.add(p2); // {x:10,y:30}
继承(Inheritance)
TypeScript中的类支持使用extends关键字单一继承
父类构造函数使用super调用,父类方法使用super.方法名调用
-
class Point3D extends Point {
-
z: number;
-
constructor(x: number, y: number, z: number) {
-
super(x, y);
-
this.z = z;
-
}
-
add(point: Point3D) {
-
var point2D = super.add(point);
-
return new Point3D(point2D.x, point2D.y, this.z point.z);
-
}
-
}
静态成员(Statics)
TypeScript类支持类的所有实例共享的static属性。放置和访问静态成员的自然位置是类本身。
-
class Something {
-
static instances = 0;
-
constructor() {
-
Something.instances ;
-
}
-
}
-
-
var s1 = new Something();
-
var s2 = new Something();
-
console.log(Something.instances); // 2
访问修饰符(Access Modifiers)
使用不同修饰符的属性或方法的可访问性:
可以访问的地方 | public | protected | private |
---|---|---|---|
类(class) | yes | yes | yes |
子类(class children) | yes | yes | no |
类的实例(class instances) | yes | no | no |
未指定时默认为public
Abstract修饰符
抽象可以被认为是一个访问修饰符。我们将其单独呈现,因为与前面提到的修饰符不同,它可以在类上,也可以在类的任何成员上。
具有抽象修饰符主要意味着不能直接调用此类功能,并且必须由子类提供该功能。
抽象类不能直接实列化,抽象方法不能直接使用,必须在子类中实现后才能使用。
构造方法
构造方法不是必须的
构造方法的参数前可以加访问修饰符,对应的变量会自动在类内定义,可以在其他地方直接使用
-
class Foo {
-
constructor(public x:number) {
-
}
-
}
可以在构造方法外进行变量初始化
-
class Foo {
-
members = []; // 无构造函数直接初始化成员变量
-
add(x) {
-
this.members.push(x);
-
}
-
}
箭头函数/Lambda函数
与函数型语言相比,JavaScript有必须频繁输入function的倾向。使用箭头函数可以简单地创建函数
var inc = (x)=>x 1;
箭头函数中的this代表周围上下文,不会因为调用者不同发生改变
-
function Person(age) {
-
this.age = age;
-
this.growOld = () => {
-
this.age ;
-
}
-
}
-
var person = new Person(1);
-
setTimeout(person.growOld,1000);
-
// 输出为2,如果不使用箭头函数输出为1
-
setTimeout(function() { console.log(person.age); },2000);
箭头函数的必要性
除了能得到简洁的语法之外,如果想让其他的东西调用函数的话,只要使用箭头函数就可以了。
-
var growOld = person.growOld;
-
// Then later someone else calls it:
-
growOld();
箭头函数可以继承
子类中使用this调用父类中的箭头函数
-
子类中使用this调用父类中的箭头函数
-
class Adder {
-
constructor(public a: number) {}
-
add = (b: number): number => {
-
return this.a b;
-
}
-
}
-
class Child extends Adder {
-
callAdd(b: number) {
-
return this.add(b);
-
}
-
}
-
// Demo to show it works
-
const child = new Child(123);
-
console.log(child.callAdd(123)); // 246
返回单一对象的箭头函数
-
var foo = () => ({
-
bar: 123
-
});
可变个数参数
参数个数不固定,剩余的参数会以数组的形式接收
-
function iTakeItAll(first, second, ...allOthers) {
-
console.log(allOthers);
-
}
-
iTakeItAll('foo', 'bar'); // []
-
iTakeItAll('foo', 'bar', 'bas', 'qux'); // ['bas','qux']
let
JavaScript中的var定义的变量作用域为函数内
let定义的变量作用域为块内
-
var foo = 123;
-
if (true) {
-
var foo = 456;
-
}
-
console.log(foo); // 456
-
let foo = 123;
-
if (true) {
-
// 生成JS时发现重名会自动改名
-
let foo = 456;
-
}
-
console.log(foo); // 123
闭包时let使用的是变量的当时值,var使用最终值
-
var funcs = [];
-
for (var i = 0; i < 3; i ) {
-
funcs.push(function() {
-
console.log(i);
-
})
-
}
-
for (var j = 0; j < 3; j ) {
-
// 输出全部为3
-
funcs[j]();
-
}
-
var funcs = [];
-
for (let i = 0; i < 3; i ) { // 这里使用的let
-
funcs.push(function() {
-
console.log(i);
-
})
-
}
-
for (var j = 0; j < 3; j ) {
-
// 输出为0,1,2
-
funcs[j]();
-
}
const
const是ES6/TypeScript提供的一个非常受欢迎的添加。它允许您对变量保持不变。从文档和运行时的角度来看,这都很好。
const foo = 123;
const声明常量时必须同时初始化,之后值不能改变
如果保存的是对象,对象的引用不能变,但是对象内的值可以变
-
const foo = { bar: 123 };
-
foo = { bar: 456 }; // 报错
-
foo.bar = 456; // 允许
const的作用域与let一致,都是块内
-
const foo = 123;
-
if (true) {
-
const foo = 456; // 允许定义块内使用的另一个foo
-
}
解构
可以使用解构取出对象的部分属性或者数组的部分值
对象的解构
-
var rect = { x: 0, y: 10, width: 15, height: 20 };
-
var {x, y, width, height} = rect;
-
console.log(x, y, width, height); // 0,10,15,20
-
-
rect.x = 10;
-
({x, y, width, height} = rect); // 使用外括号分配给现有变量
-
console.log(x, y, width, height); // 10,10,15,20
要将展开的变量分配给新变量名,请执行以下操作:
-
const obj = {"some property": "some value"};
-
const {"some property": someProperty} = obj;
-
console.log(someProperty === "some value"); // true
也可以使用解构获取结构的深层数据
-
var foo = { bar: { bas: 123 } };
-
var {bar: {bas}} = foo; // 相当于: `var bas = foo.bar.bas;`
对象解构中使用Rest
可以拆出指定项目以外的其他项目作为一个单独的对象
-
var {w, x, ...remaining} = {w: 1, x: 2, y: 3, z: 4};
-
console.log(w, x, remaining); // 1, 2, {y:3,z:4}
数组的解构
-
var x = 1, y = 2;
-
[x, y] = [y, x];
-
console.log(x, y); // 2,1
数组解构中使用Rest
可以拆出指定下标以外的其他项目作为一个单独的数组
-
var [x, y, ...remaining] = [1, 2, 3, 4];
-
console.log(x, y, remaining); // 1, 2, [3,4]
可以跳过不需要的下标
-
var [x, , ...remaining] = [1, 2, 3, 4];
-
console.log(x, remaining); // 1, [3,4]
展开运算符
把对象或数组的元素平铺展开
展开运算符是一种很好的语法,可以让JavaScript中常用的apply的this参数不必传递难以理解的null
另外,通过使用分割数组或代入其他数组的语法,可以用简单的代码对部分数组进行处理
对象的展开
展开时如果有同名,后面的值会覆盖前面的值
-
const point2D = {x: 1, y: 2};
-
const anotherPoint3D = {x: 5, z: 4, ...point2D};
-
console.log(anotherPoint3D); // {x: 1, y: 2, z: 4}
-
const yetAnotherPoint3D = {...point2D, x: 5, z: 4}
-
console.log(yetAnotherPoint3D); // {x: 5, y: 2, z: 4}
-
const foo = {a: 1, b: 2, c: 0};
-
const bar = {c: 1, d: 2};
-
const fooBar = {...foo, ...bar}; // `fooBar`: {a: 1, b: 2, c: 1, d: 2}
数组的带入
-
var list = [1, 2];
-
list = [...list, 3, 4];
-
console.log(list); // [1,2,3,4]
可以展开到任意位置
-
var list = [1, 2];
-
list = [0, ...list, 4];
-
console.log(list); // [0,1,2,4]
for...of
数组循环
-
var someArray = [9, 2, 5];
-
for (var item of someArray) {
-
console.log(item); // 9,2,5
-
}
可以把字符串拆成字符
-
var hello = "is it me you're looking for?";
-
for (var char of hello) {
-
console.log(char); // is it me you're looking for?
-
}
限制
如果您的目标不是ES6或更高版本,则生成的代码假设对象上存在属性长度,并且可以通过数字(例如obj[2])对对象进行索引。因此,对于这些遗留的JS引擎,它只在字符串和数组上受支持。
如果TypeScript可以看到你没有使用数组或字符串,它会给你一个明确的错误“不是数组类型或字符串类型”。
Iterator
它本身不是TypeScript或ES6的功能,而是面向对象编程语言中常见的“行为设计模式”。这通常是实现以下接口的对象:
-
interface Iterator<T> {
-
next(value?: any): IteratorResult<T>;
-
return?(value?: any): IteratorResult<T>;
-
throw?(e?: any): IteratorResult<T>;
-
}
-
interface IteratorResult<T> {
-
done: boolean;
-
value: T;
-
}
如果只实现Iterator接口,可以使用next方法遍历
如果只使用[Symbol.iterator]符号,可以使用for...of,但不能使用next方法遍历
如果实现TypeScript的IterableIterator接口,可以同时使用next方法和for...of
-
class Frame implements IterableIterator<Component> {
-
private pointer = 0;
-
constructor(public name: string, public components: Component[]) {}
-
-
public next(): IteratorResult<Component> {
-
if (this.pointer < this.components.length) {
-
return {
-
done: false,
-
value: this.components[this.pointer ]
-
}
-
} else {
-
return {
-
done: true,
-
value: null
-
}
-
}
-
}
-
-
[Symbol.iterator](): IterableIterator<Component> {
-
return this;
-
}
-
-
}
迭代器不仅可以单纯返回元素,还可以用于递归计算,比如计算Fibonacci数列
-
class Fib implements IterableIterator<number> {
-
protected fn1 = 0;
-
protected fn2 = 1;
-
constructor(protected maxValue?: number) {}
-
-
public next(): IteratorResult<number> {
-
var current = this.fn1;
-
this.fn1 = this.fn2;
-
this.fn2 = current this.fn1;
-
if (this.maxValue != null && current >= this.maxValue) {
-
return {
-
done: true,
-
value: null
-
}
-
}
-
return {
-
done: false,
-
value: current
-
}
-
}
-
[Symbol.iterator](): IterableIterator<number> {
-
return this;
-
}
-
}
-
let fib = new Fib();
-
-
fib.next() //{ done: false, value: 0 }
-
fib.next() //{ done: false, value: 1 }
-
fib.next() //{ done: false, value: 1 }
-
fib.next() //{ done: false, value: 2 }
-
fib.next() //{ done: false, value: 3 }
-
fib.next() //{ done: false, value: 5 }
-
-
let fibMax50 = new Fib(50);
-
console.log(Array.from(fibMax50)); // [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]
-
-
let fibMax21 = new Fib(21);
-
for(let num of fibMax21) {
-
console.log(num); //Prints fibonacci sequence 0 to 21
-
}
模板文字
在语法上,字符串使用反引号(`)代替单引号(')或双引号(“)。
字符串展开(String Interpolation)
${}中间可以是变量或表达式,最后生成的字符串会把实际的值进行代入
-
var lyrics = 'Never gonna give you up';
-
var html = `<div>${lyrics}</div>`;
-
console.log(`1 and 1 make ${1 1}`);
多行文字
-
var lyrics = `Never gonna give you up
-
Never gonna let you down`;
标记的模板
您可以在模板字符串之前放置一个函数(称为标记),这样它就有机会预处理模板字符串文字加上所有占位符表达式的值,并返回结果。
所有静态文字都作为第一个参数的数组传入。占位符表达式的所有值都作为剩余的参数传入。最常见的情况是,您只需要使用rest参数将这些参数转换为数组。
-
var say = "a bird in hand > two in the bush";
-
var html = htmlEscape `<div> I would just like to say : ${say}</div>`;
-
-
// 您可以将占位符声明为任意类型的数组。TypeScript都会键入check,以确保用于调用标记的占位符与注释匹配。
-
// 例如,如果你希望处理字符串或数字:...placeholders:(string | number)[]
-
function htmlEscape(literals: TemplateStringsArray, ...placeholders: string[]) {
-
let result = "";
-
-
// 将文字与占位符交错
-
for (let i = 0; i < placeholders.length; i ) {
-
result = literals[i];
-
result = placeholders[i]
-
.replace(/&/g, '&')
-
.replace(/"/g, '"')
-
.replace(/'/g, ''')
-
.replace(/</g, '<')
-
.replace(/>/g, '>');
-
}
-
-
// 追加最后的文字
-
result = literals[literals.length - 1];
-
return result;
-
}
Promise
Promise类存在于许多时髦的JavaScript引擎中,可以轻松地polyfill。想使用Promise的理由是,对于异步/回调风格的代码,可以使用同步处理的写法处理错误。
Promise链
Promise的链条是使用Promise的最大优点。一旦取得Promise,从那个时候开始,可以使用then函数制作Promise的链。
如果您从链中的任何函数返回promise,那么只有在解析值后才会调用.then:
-
Promise.resolve(123)
-
.then((res) => {
-
console.log(res); // 123
-
return 456;
-
})
-
.then((res) => {
-
console.log(res); // 456
-
return Promise.resolve(123); // 返回resolve的Promise
-
})
-
.then((res) => {
-
console.log(res); // 123 : 使用resolve的值调用后面的.then
-
return 123;
-
})
可以将链前面部分的错误处理聚合为单个catch
-
Promise.reject(new Error('something bad happened'))
-
.then((res) => {
-
console.log(res); // 不会调用
-
return 456;
-
})
-
.then((res) => {
-
console.log(res); // 不会调用
-
return 123;
-
})
-
.catch((err) => {
-
console.log(err.message); // something bad happened
-
});
catch实际上返回一个新的promise(有效地创建了一个新promise链):
-
Promise.reject(new Error('something bad happened'))
-
.then((res) => {
-
console.log(res); // 不会调用
-
return 456;
-
})
-
.catch((err) => {
-
console.log(err.message); // something bad happened
-
return 123;
-
})
-
.then((res) => {
-
console.log(res); // 123
-
})
在then(或catch)中抛出的任何同步错误都会导致返回的promise失败:
-
Promise.resolve(123)
-
.then((res) => {
-
throw new Error('something bad happened'); // 抛出同步错误
-
return 456;
-
})
-
.then((res) => {
-
console.log(res); // 不会调用
-
return Promise.resolve(789);
-
})
-
.catch((err) => {
-
console.log(err.message); // something bad happened
-
})
对于给定的错误,只调用相关的(最近的尾部)catch(因为catch启动了一个新的promise链)。
-
Promise.resolve(123)
-
.then((res) => {
-
throw new Error('something bad happened'); // 抛出同步错误
-
return 456;
-
})
-
.catch((err) => {
-
console.log('first catch: ' err.message); // something bad happened
-
return 123;
-
})
-
.then((res) => {
-
console.log(res); // 123
-
return Promise.resolve(789);
-
})
-
.catch((err) => {
-
console.log('second catch: ' err.message); // 不会调用
-
})
只有在前一个链中出现错误时才会调用catch:
-
Promise.resolve(123)
-
.then((res) => {
-
return 456;
-
})
-
.catch((err) => {
-
console.log("HERE"); // 不会调用
-
})
创建Promise
-
import fs = require('fs');
-
function readFileAsync(filename: string): Promise<any> {
-
return new Promise((resolve,reject) => {
-
fs.readFile(filename,(err,result) => {
-
if (err) reject(err);
-
else resolve(result);
-
});
-
});
-
}
并行处理
Promise提供了一个静态Promise.all函数,您可以使用它来等待n个Promise完成,全部完成后才执行then。
-
let item1, item2;
-
Promise.all([loadItem(1), loadItem(2)])
-
.then((res) => { // 响应内容为数组,与all里的Promise对应
-
[item1, item2] = res;
-
console.log('done');
-
});
Promise提供了一个静态Promise.race函数,可以在多个Promise中的任意一个完成时就返回。
-
Promise.race([task1, task2]).then(function(value) {
-
console.log(value); // "one"
-
// 响应内容为最早完成的Promise任务的返回值
-
});
将回调函数转换为Promise
-
const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
-
delay(1000)
-
.then(() => {
-
})
生成器
function *是用于创建生成器函数的语法。调用生成器函数将返回生成器对象。生成器对象遵循迭代器接口(即next、return和throw函数)。
生成器函数可用于创建惰性迭代器
-
function* idMaker(){
-
let index = 0;
-
while(index < 3)
-
yield index ;
-
}
-
-
let gen = idMaker();
-
console.log(gen.next()); // { value: 0, done: false }
-
console.log(gen.next()); // { value: 1, done: false }
-
console.log(gen.next()); // { value: 2, done: false }
-
console.log(gen.next()); // { done: true }
外部控制执行
本质上,函数可以暂停其执行,并将剩余函数执行的控制(命运)传递给调用方。
-
function* generator(){
-
console.log('Execution started');
-
yield 0;
-
console.log('Execution resumed');
-
yield 1;
-
console.log('Execution resumed');
-
}
-
-
var iterator = generator();
-
console.log('Starting iteration'); // 它在生成器函数的主体之前运行
-
console.log(iterator.next()); // { value: 0, done: false }
-
console.log(iterator.next()); // { value: 1, done: false }
-
console.log(iterator.next()); // { value: undefined, done: true }
当为生成器对象调用next时,函数只执行一次
函数在yield语句出现时立即暂停
函数在next被调用时重新启动
yield暂停生成器函数的通信,允许将控制传递到函数外部
可以从外部向生成器函数主体发送值
从外部,可以对生成器函数主体抛出异常
-
function* generator() {
-
var bar = yield 'foo'; // bar可以是any类型
-
console.log(bar); // bar!
-
}
-
-
const iterator = generator();
-
// 开始执行,直到我们获得第一个输入值
-
const foo = iterator.next();
-
console.log(foo.value); // foo
-
// 传入'bar'再执行
-
const nextThing = iterator.next('bar');
-
-
function* generator() {
-
try {
-
yield 'foo';
-
} catch(err) {
-
console.log(err.message); // bar!
-
}
-
}
-
-
var iterator = generator();
-
// 开始执行,直到我们获得第一个输入值
-
var foo = iterator.next();
-
console.log(foo.value); // foo
-
// 继续执行抛出异常
-
var nextThing = iterator.throw(new Error('bar'));
async await
如果Promise使用了await关键字,则暂停执行JavaScript代码。然后,仅当从该函数返回的Promise完成时,代码才重新开始执行。
如果Promise成功,await返回响应内容
如果Promise失败,抛出可以同步处理的异常
-
async function foo() {
-
try {
-
var val = await getMeAPromise();
-
console.log(val);
-
} catch(err) {
-
console.log('Error: ', err.message);
-
}
-
}
在异步函数的开头使用async关键字,async函数总是返回Promise
-
function delay(milliseconds: number, count: number): Promise<number> {
-
return new Promise<number>(resolve => {
-
setTimeout(() => {
-
resolve(count);
-
}, milliseconds);
-
});
-
}
-
async function dramaticWelcome(): Promise<void> {
-
console.log("Hello");
-
-
for (let i = 0; i < 5; i ) {
-
const count:number = await delay(500, i);
-
console.log(count);
-
}
-
-
console.log("World!");
-
}
-
-
dramaticWelcome();
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhihbfej
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
excel下划线不显示怎么办
PHP中文网 06-23 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel图片置于文字下方的方法
PHP中文网 06-27 -
微信运动停用后别人还能看到步数吗
PHP中文网 07-22