# TypeScript 对象类型
对象定义:
// 对象类型
const emp1 = {
name:'hedon',
gender: 'male',
salary: 8000,
bonus: undefined as (number | undefined)
}
// 访问对象属性
console.log(`${emp1.name} has a salary of ${emp1.salary}`)
// 设置属性值
emp1.bonus = 10000
// 无属性,编译报错
// emp1.hello = 10000
JSON 变换:
// JSON -> Object
const emp2 = JSON.parse(str)
// Object -> JSONStr
const str = JSON.stringify(emp2)
对象方法:
const emp1 = {
name: 'hedon',
salary: 8000,
bonus: undefined as (number | undefined),
performance: 3.5,
// 对象方法
updateBonus(){
// 一定要带 this 或者 emp1
if(!this.bonus) {
this.bonus = this.salary * this.performance
}
},
}
emp1.updateBonus()