TypeScript应用 极速上手(15)

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')
    }
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DreamCatcher

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值