- 上回书说到我被 Typescript的类型断言给尬住了。当时我直接跑到厕所,吨吨吨喝了三斤水。平静一下。再看看其他大佬们的汇总。然后继续学习吧!!!
类型断言
看过很多人的言论,就是一句话。作为写代码的人,这是一个什么类型
as 语法
let strValue: any = 'this is string type';
let strLength: number = (strValue as string).length;
尖括号语法 但是尖括号语法会与react中JSX产生语法冲突 产生编译错误。 推荐使用as语法
let strValue = 'this is a string type';
let strLength = (<string>strValue).length;
非空断言
在上下文中当类型检查器无法断定类型时,一个新的后缀表达式操作符 ! 可以用于断言操作对象是非 null 和非 undefined 类型。具体而言,x! 将从 x 值域中排除 null 和 undefined 。
function getMsg(msg: undefined | null | string ) {
const str: string = msg; // Type 'undefined' is not assignable to type 'string'
const str1: string = msg!; // ok
}
// 在调用getMsg的时候 msg 有可能是 undefined 或 null
// 所以当 赋值 str 是string 类型的时候 就会报错
// 使用 ! 修饰符可以排出 undefined 和 null
// ! 表示可以确定某个标识(变量)是有值的, 可以跳过ts在编译阶段对它的检测
type numFn = () => number;
function getMsg(numMsg: numFn | undefined) {
// Object is possibly 'undefined'.
// Cannot invoke an object which is possibly 'undefined'.
const num1 = numMsg(); // error
const num2 = numMsg!(); // ok
}
getMsg(function (){
return 1
})
//getMsg方法中numFn 如果是undefined
//const num1 = numMsg();会报错 使用`!`排除undefined情况。
确定赋值断言
允许在实例属性和变量声明后加一个 ! 号,从而告诉 TypeScript 这个属性会被明确赋值
let x: number;
initialize();
// Variable 'x' is used before being assigned.(2454)
console.log(2 * x); // Error
function initialize() {
x = 10;
}
//报错信息在赋值前使用了变量x
将x后加一个!,告诉他断言这个x一定被赋值
let x!: number;
initialize();
console.log(2 * x); // ok
function initialize() {
x = 10;
}
打完收工!顺便提一句官方Playground感觉有些错误,并不会显示,还是老老实实在IDE上敲打。