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 编译器就会知道该属性会被明确地赋值。