1、可选参数串联与非空断言
(1)可选参数串联(?),只要有一个值是undefined 则结果就为undefined
(2)非空断言(!):如果字段不存在,则会抛出ERR
interface Employee {
name?:{
first?:string
last:string
}
salary:number
bonus?:number
}
function hasBadName(e:Employee){
// return e.name?.first?.startsWith('L') //可选参数串联(?),只要有一个值是undefined 则结果就为undefined
return e.name!.first!.startsWith('L') //非空断言(!):如果字段不存在,则会抛出ERR
}
console.log(hasBadName({
name:{
// first:'james',
last:'smith',
},
salary:8000
})) //false
2、接口的扩展
通过extends关键字
interface HasName {
name?:{
first?:string
last:string
}
}
interface Employee extends HasName {
salary:number
bonus?:number
}
function hasBadName(e:Employee){
return e.name?.first?.startsWith('L') //可选参数串联(?),只要有一个值是undefined 则结果就为undefined
//return e.name!.first!.startsWith('L') //非空断言:如果字段不存在,则会抛出ERR
}
console.log(hasBadName({
name:{
first:'james',
last:'smith',
},
salary:8000
}))
3、类型的并(|共有属性)
interface MyButton {
visible:boolean
enabled:boolean
onClick():void
}
interface MyImgs {
visible:boolean
src:string
width:number
height:number
}
function processElement(e:MyButton | MyImgs){
//参数e取的是接口类型MyButton和MyImgs的并集:visible
}
4、类型断言(as)
interface MyButton {
visible:boolean
enabled:boolean
onClick():void
}
interface MyImgs {
visible:boolean
src:string
width:number
height:number
}
function processElement(e:MyButton | MyImgs){
//判断是否为Button, 类型断言as
//只有MyButton才会有onClick函数,as any 避开编译器判断,由自己决定
if ((e as any).onClick){
const btn = e as MyButton
btn.onClick()
}else {
const img = e as MyImgs
console.log(img.src)
}
}
5、类型判断(is)
interface MyButton {
visible:boolean
enabled:boolean
onClick():void
}
interface MyImgs {
visible:boolean
src:string
width:number
height:number
}
//高级写法: 类型判断 is
function isButton(e:MyButton | MyImgs):e is MyButton {
return (e as MyButton).onClick !== undefined
}
function processElement(e:MyButton | MyImgs){
//通过类型判断
if (isButton(e)){
e.onClick()
}else {
console.log(e.src)
}
processElement({
visible:true,
enabled:true,
onClick(){
console.log('MyButton onClick')
}
})