Typescript - 类型断言

原文:TypeScript基本知识点整理

 

零、序言

  类型断言,可以用来手动指定一个值的类型。

  给我的感觉,和 java 中的强制类型转换很像。

  常常和联合类型配合使用,如:

// 错误示例
function f13(name : string, age : string | number) {
     if (age.length) { //报错
         console.log(age.length) //报错
     }  else {
         console.log(age.toString)
     }

 }

 f13('ljy', 21)   
//Property 'length' does not exist on type 'string |number'.Property 'length' does not exist on type 'number'

// 使用类型断言示例
function f14(name : string, age : string | number) {
    if ((<string>age).length) {//断言
        console.log((<string>age).length)//断言
    }  else {
        console.log(age.toString)
    }

}
f14('ljy', 21)

 

注意事项:

  类型断言并不是普通意义上的类型转换,断言成一个联合类型中不存在的类型是不允许的:

function toBoolean(something: string | number): boolean {
    return <boolean>something;
}
// Type 'string | number' cannot be converted to type 'boolean'

 

转载于:https://www.cnblogs.com/cc-freiheit/p/11051992.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值