『TypeScript』类型断言

本文详细介绍了TypeScript中的类型断言和非空断言。通过类型断言,开发者可以告诉编辑器变量的具体类型,例如使用`as`关键字或尖括号`<>`。非空断言`!`用于排除`null`和`undefined`,确保变量在使用时已赋值。在函数调用和实例属性声明中,非空断言同样适用,帮助开发者跳过TypeScript对可能未定义值的检查。
摘要由CSDN通过智能技术生成

1. 类型断言

通过类型断言这种方式可以告诉编辑器,‘我很清楚这是一个什么类型’;

类型断言的两种形式:

1.  as 语法

let strValue: any = 'this is string type';
let strLength: number = (strValue as string).length;

2. “尖括号”<> 语法

let strValue = 'this is a string type';
let strLength = (<string>strValue).length;

2. 非空断言

x! 将从 x 值中排出 null 和 undefined。

1. 忽略 undefined 和 null 类型

function myFn(msg: string | undefined | null) {
    const str: string = msg; //  Type 'undefined' is not assignable to type 'string'
    const str: string = msg!; // ok
}
// 在调用myFn的时候 msg 有可能是 undefined 或 null
// 所以当 赋值 str 是string 类型的时候 就会报错
// 使用 ! 修饰符可以排出 undefined 和 null
// ! 表示可以确定某个标识(变量)是有值的, 可以跳过ts在编译阶段对它的检测

 2. 调用函数是忽略 undefined 类型

type numFn = () => number;
function myFn(numMsg: numFn | undefined) {
    // Object is possibly 'undefined'.
    // Cannot invoke an object which is possibly 'undefined'.
    const num1 = numMsg(); // error
    const num2 = numMsg!(); // ok
}
myFn(function (){
    return 1
})

3.确定赋值断言

允许在实例属性和变量声明后加一个 ! 号,从而告诉 TypeScript 这个属性会被明确赋值。

let x: number;
setX();
// Variable 'x' is used before being assigned.
// 变量“x”在赋值之前使用
console.log(2 * x); // Error

function setX() {
  x = 10;
}

使用 确定赋值断言

let x!: number;

function setX() {
  x = 10;
}

setX();
console.log(2 * x); // ok ===> 20

通过 let x!: number; 确定赋值断言,TypeScript 编译器就会知道该属性会被明确地赋值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值