ts中?跟readonly的区别
区别
? 是代表可读可写的(可有可无)
readonly代表只能读取不能修改
代码
(()=>{
interface newPerson{
id?:number | string,
readonly name:string | number
}
let newChildren:newPerson = {
id:1,
name:"张三"
}
console.log(newChildren); // {id: 1, name: "张三"}
})()
修改后代码
interface newPerson{
id?:number | string,
readonly name:string | number
}
let newChildren:newPerson = {
id:1,
name:"张三"
}
newChildren.id = 2
newChildren.name = "" // 会报错
console.log(newChildren); // {id: 2, name: "张三"}