interface SquareConfig {
/**
* 这就是可选属性,意思一目了然。
* 在某些情况下,某个可选属性存在。在某些情况下,某个可选属性不存在。
* 可选属性与之相对的就是必选属性
*/
color? : string;
width? : number;
}
function area(square: SquareConfig) {
let newSquare = {color: '红色', width: 100, area: 10000}
if (square.color) {
newSquare.color = square.color;
}
if (square.width) {
newSquare.width = square.width;
newSquare.area = square.width * square.width;
}
return newSquare;
}
let square = {color: 'red'}
let rectangle = area(square);
console.log(rectangle.color);
console.log(rectangle.area);
使用接口实现typesrcipt中的可选属性
最新推荐文章于 2024-05-02 09:17:56 发布