TS 类型断言

Typescript允许你覆盖它的判断,并且能以任何你想要的方式分析它,这种机制被称为类型断言。

类型断言的两种方式:

1.as关键字

interface SquareConfig {
  color?: string;
  width?: number;
}

function createSquare(config: SquareConfig) {
  // ...
}

let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);

2.尖括号<>

let someValue: any = 'this is a string'
let strLength: number = (<string>someValue).length

一般情况建议使用as关键字来断言,尖括号断言在jsx中会有歧义,因此建议统一使用as。

注意:

类型断言只能够欺骗typescript编译器,无法避免运行时的错误。

类型断言和类型转换对比

类型断言只会影响typescript编译时的类型,类型断言在编译结果中会被删除。上述代码经过typescript编译后会变成:

let someValue = 'this is a string'
let strLength = someValue.length

而类型转换会改变变量的值:

let someValue: any = 'this is a string'
let strLength: number = (<string>someValue).length  // 类型断言
let someValue2 =  Boolean(someValue) // 类型转换

// someValue2 => true

类型断言和类型声明对比:

注意优先使用类型声明,代码更优雅,代码质量高

interface SquareConfig {
  color?: string;
  width?: number;
}

function createSquare(config: SquareConfig): SquareConfig{
  // ...
  return config
}

// 类型声明
const mySquare: SquareConfig = createSquare({ width: 100 });

// 类型转换
const mySquare2 = createSquare({ width: 100}) as SquareConfig

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值