web前端全系列 教程
1839个小节阅读:2243.4k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
接口里的属性不全都是必需的。 有些是只在某些条件下存在,或者根本不存在。 可选属性在应用 “option bags” 模式时很常用,即给函数传入的参数对象中只有部分属性赋值了
带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个 ?
符号
xxxxxxxxxx
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig) {
let newSquare = {
color: "white",
area: 100
}
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({ color: "black" });
console.log(mySquare)
可选属性的好处之一是可以对可能存在的属性进行预定义,好处之二是可以捕获引用了不存在的属性时的错误。 比如,我们故意将 createSquare
里的 color
属性名拼错,就会得到一个错误提示
xxxxxxxxxx
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config:SquareConfig){
let newSquare = { color: "white", area: 100 };
if (config.clor) {
// Error: Property 'clor' does not exist on type 'SquareConfig'
newSquare.color = config.clor;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({ color: "black" });
实时效果反馈
1. 在TypeScript中,接口的可选属性如何定义:
A color?: string
B color:: string
C color!: string
D color: string
答案
1=>A