//可选属性和只读属性
interface Square {
color: string
area: number
}
// ?: 表示是可选的属性
interface SquareConfig {
color?:string
width?:number
}
const createSquare = (config: SquareConfig):Square => {
let newSquare = {
color: 'white',
area: 100
}
if(config.color) {
newSquare.color = config.color
}
if(config.width) {
newSquare.area = Math.pow(config.width,2)
}
return newSquare;
}
const mySquare = createSquare({color: 'red'})
console.log(mySquare)
// readonly--只读
interface Point {
readonly x:number
readonly y:number
}
let p1:Point = {
x: 10,
y: 20
}
// p1.x=9//报错--不能对只读属性做修改
let a:number[] = [1,2,3]
let ro:ReadonlyArray<number> = a
// ro[0] = 2//报错--ro数组是只读的
// a = ro//赋值回去也不行,因为他们两个数组的类型已经不匹配了
// 想要赋值回去使用as修改数据的属性
a = ro as number[]