//定义type类型
type person={
name:string,
age:number,
eat(thing:string):void,
hobby?:string
}
//绑定类型
const xiaomi:person={
name:'Hx',
age:16,
eat(thing){console.log(thing)}
}
//调用对象方法(因为hobby设置为可选属性,所有必须先得判断是否存在hobby,才来使用它)
//1.采用可选链来判断hobby是否存在(推荐)
xiaomi.hobby?.concat()
//2.传统
if(xiaomi.hobby){
xiaomi.hobby.concat()
}
//3.&&运算符
xiaomi.hobby&&xiaomi.hobby.concat()
TypeScript中对于设置对象的‘可选属性’的几个注意点
最新推荐文章于 2024-07-24 10:40:52 发布