常用语法

1 ES 技巧

① JSON

JS 操作 JSON 常用方法

1、字符串转对象

//将js对象转化为JSON字符
var obj2 = JSON.parse(str1);

2、对象转字符串

var jsonstr = JSON.stringify(jsonObject);

② type 定义

这里使用&可以实现类似的效果,如下:

interface Foo {
a: string;
}
type Bar = Foo & {
b: number;
};

https://blog.51cto.com/15077562/2608878

常用语法:

Omit去掉
Partial可选
keyof
Pick选取
extends 继承
Dictionary&Many

③ 赋值析构

下面是常用的,详细的请看

改变变量名

let node = {
type: 'Identifier',
name: 'foo',
};
let { type: localType, name: localName } = node;
console.log(localType); // "Identifier"
console.log(localName); // "foo"

默认值

let node = {
type: 'Identifier',
name: 'foo',
};
let { type, name, value = true } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // true

嵌套对象解构

let node = {
type: 'Identifier',
name: 'foo',
loc: {
start: {
line: 1,
column: 1,
},
end: {
line: 1,
column: 4,
},
},
};
let {
loc: { start },
} = node;
console.log(start.line); // 1
console.log(start.column); // 1

④ 类型转换

const groupId = Number(id);
const groupId = id as number;
//下面的在tsx中不能使用
const groupId = <number>id;