查看: 102|回复: 0

Typescript - 类型断言

[复制链接]

4

主题

0

回帖

0

积分

热心网友

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2009-9-27
发表于 2019-7-1 08:37:00 | 显示全部楼层 |阅读模式

原文: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
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

圆梦公社,专注于为全球华人提供纯粹技术交流的地方,请勿发布任何政治及违法的言论。如有相关侵权、举报、投诉及建议等,请发 E-mail:[email protected]

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部