【前端,TypeScript】TypeScript速成(五):对象类型
对象类型
对于 JavaScript 而言,不需要有一个类的定义,就可以创建一个对象,这是 JavaScript 的一个优点,在快速开发当中非常有用。TypeScript 在对象方面与 JavaScript 相同。
对象的定义
最简单的定义如下:
const emp1 = {
name: 'John',
gender: 'Male',
salary: 8000
}
console.log(emp1)
// out
[LOG]: {
"name": "John",
"gender": "Male",
"salary": 8000
}
定义了对象之后,不能在定义之外为对象加入成员,想要加入新的成员必须返回定义处添加:
更新的定义如下:
const emp1 = {
name: 'John',
gender: 'Male' as 'Male' | 'Female' | 'Other' | 'Unknown',
salary: 8000,
performance : 3.5,
bonus: undefined as (number | undefined),
}
最后一行的bonus: undefined as (number | undefined)
意思是 bonus 成员的初值是 undefined,但是它可以被赋值为 undefined 或 number 类型。在学习接口之后,可以使用可选字段的方式简化这部分的流程。
在类型定义的基础上,还可以进行类型的嵌套定义,比如:
const emp1 = {
name: {
first: 'John',
last: 'David'
},
gender: 'Male' as 'Male' | 'Female' | 'Other' | 'Unknown',
salary: 8000,
performance : 3.5,
bonus: undefined as (number | undefined),
}
// output
[LOG]: {
"name": {
"first": "John",
"last": "David"
},
"gender": "Male",
"salary": 8000,
"performance": 3.5,
"bonus": 28000
}
输出的格式非常的眼熟,实际上该输出的格式就是 json(JavaScript Object Notation)。
将对象转为字符串
使用 JSON.stringify 方法:
const s: string = JSON.stringify(emp1)
console.log(s)
// out
[LOG]: "{"name":{"first":"John","last":"David"},"gender":"Male","salary":8000,"performance":3.5,"bonus":28000}"
使用 JSON.parse 可以完成字符串转 JSON:
const s: string = JSON.stringify(emp1)
let emp2 = JSON.parse(s)
console.log(emp2)
// out
[LOG]: {
"name": {
"first": "John",
"last": "David"
},
"gender": "Male",
"salary": 8000,
"performance": 3.5,
"bonus": 28000
}
emp2 的类型是 any,因为编译器不知道 parse 的字符串来自于哪里。在学习接口之后我们将知道如何给 emp2 一个正确的类型。
emp1 和 emp2 是不相等的,因为它们是两个不同的类型。可以通过第三方的库完成值的比较。