Typescript
Playground 快速实验
Run Single Ts file
- ts编译js后运行
tsc filepath.ts && node filepath.js
- ts-node 直接运行
ts-node filepath.ts
Data Types
检查 type 类型
涉及到 null/undefined 值的写法
nullish coalescing operator
var current = stack.pop() || null // 不正确
var current = stack.pop() ?? null; // 正确
console.log(0 || null) // output: null
console.log(0 ?? null) // output: 0
The nullish coalescing operator only returns its right-hand side operand when its left-hand side operand is null
or undefined
, not when it's falsy like 0
, ''
, or false
.
值不为空才执行右边的命令
-
结合
!=
与&&
// 只有 `null` 和 `undefined` 才等于被判为 false
console.log(3 != null); // true
console.log(0 != null); // true
console.log(false != null); // true
console.log(null != null); // false
console.log(undefined != null); // falsenode = {val: 3}
node?.val != null && console.log(node.val);
node = {val: 0}
node?.val != null && console.log(node.val);
node = {}
node?.val != null && console.log(node.val); -
nullish coalescing operator
在符号左边为
null
或者undefined
的时候,返回右边的值(node?.val ?? false) && console.log(1);
-
错误写法
// 当值为 0 的时候,虽然不为空,但仍然被视为 false,不会执行右边的命令
current.left && stack.push(current.left);
0 && console.log(1) // 虽然左边不为null/undefined, 但是右边仍然不会被执行, 1 不会被打印出来
Data type convert 数值类型转换
string --> number
https://www.freecodecamp.org/news/how-to-convert-a-string-to-a-number-in-javascript/
> var quantity = '12'
> console.log(Number(quantity))
12
> console.log(parseInt(quantity))
12
> console.log(+quantity)
12
> console.log(parseFloat('13.4'))
13.4
@Put(':id')
update(@Param('id') id: string, @Body() updateAccountDto: UpdateAccountDto) {
return this.accountService.update(+id, updateAccountDto); // +convert string into number
}
Datetime
Containers
Array
定义与赋值
-
使用数组字面量定义和初始化数组:
let numbers: number[] = [1, 2, 3, 4, 5];
-
使用Array构造函数定义和初始化数组:
let fruits: Array<string> = new Array("Apple", "Banana", "Orange");
-
定义空数组并后续赋值:
let names: string[] = [];
names = ["Alice", "Bob", "Charlie"]; -
直接赋值给数组元素:
let colors: string[] = [];
colors[0] = "Red";
colors[1] = "Green";
colors[2] = "Blue";
数组解构
-
基本数组解构:
let numbers: number[] = [1, 2]
let [first, second] = numbers;
console.log(first); // 输出: 1
console.log(second); // 输出: 2 -
忽略某些元素:
let numbers: number[] = [1, 2, 3]
let [one, , three] = numbers;
console.log(one); // 输出: 1
console.log(three); // 输出: 3