【typescript】详解ts操作符中的?、?:、?.、??、||、|、!、!.、!!
·
下面是ts中?、?.、?:、??、||、|、!、!.、!!的基本介绍:
? 表示该属性或参数为可选项
?. 可以理解为对象自动加上undefined
?: 是指可选参数或者属性
?? 表示只有当左侧为null和undefined时, 才会返回右侧的数
|| 表示只有当左侧为0、null和undefined时, 才会返回右侧的数
| 表示取值可以为多种类型中的⼀种,联合类型使⽤ | 分隔每个类型。
! 是指非空断言,告诉ts某个属性或者参数不能为空
!. 是指断言,告诉 ts 该对象里一定有某个值
!! 是指把表达式强行转换为boolean类型,常用于类型判断
一、? 相关代码
在typescript里面,有4个地方会出现问号操作符,他们分别是:
1)三元运算符
// 当 isNumber(input) 为 True 时返回 ? : 之间的部分;
// isNumber(input) 为 False 时返回 : ; 之间的部分
const a = isNumber(input) ? input : String(input);
2)可选参数or对象属性
?: 是指可选参数,可以理解为参数自动加上undefined
// 这里的 ?表示这个参数 field 是一个可选参数
function getUser(user: string, field?: string) {
}
当使用A对象属性A.B时,如果无法确定A是否为空,则需要用A?.B,表示当A有值的时候才去访问B属性,没有值的时候就不去访问,如果不使用?则会报错
const user = null;
console.log(user.account) // 报错
console.log(user?.account) // undefined
3)成员
// 这里的?表示这个name属性有可能不存在
class A {
name?: string // 可选属性
}
interface B {
pageSize: number,
pageNumber: number,
name?: string // 可选属性
}
4)安全链式调用
?.允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?.操作符的功能类似于.链式操作符,不同之处在于,在引用为空(null 或者 undefined)的情况下不会引起错误而是直接返回null or undefined
// 这里 Error对象定义的stack是可选参数,如果这样写的话编译器会提示
// 出错 TS2532: Object is possibly 'undefined'.
return new Error().stack.split('\n');
// 我们可以添加?操作符,当stack属性存在时,调用 stack.split。
// 若stack不存在,则返回空
return new Error().stack?.split('\n');
// 以上代码等同以下代码, 感谢 @dingyanhe 的监督
const err = new Error();
return err.stack && err.stack.split('\n');
二、! 相关代码
在typescript里面有3个地方会出现感叹号操作符,他们分别是:
1)一元运算符
// ! 就是将之后的结果取反,比如:
// 当 isNumber(input) 为 True 时返回 False;
// isNumber(input) 为 False 时返回True
const a = !isNumber(input);
2)成员
// 因为接口B里面name被定义为可空的值,但是实际情况是不为空的,
// 那么我们就可以通过在class里面使用!,重新强调了name这个不为空值
class A implemented B {
name!: string // 属性不能为空
}
interface B {
name?: string // 属性可以为空
}
3) !. 的意思是断言,告诉 ts 你这个对象里一定有某个值
const inputRef = useRef<HTMLEInputlement>(null);
// 定义了输入框,初始化是null,但是你在调用他的时候相取输入框的value,这时候dom实例一定是有值的,所以用断言
const value: string = inputRef.current!.value;
// 这样就不会报错了
4)强制链式调用
// 这里 Error对象定义的stack是可选参数,如果这样写的话编译器会提示
// 出错 TS2532: Object is possibly 'undefined'.
new Error().stack.split('\n');
// 我们确信这个字段100%出现,那么就可以添加!,强调这个字段一定存在
new Error().stack!.split('\n');
三、?? 、 || 和 | 的意思有点相似,但是又有点区别, ?? 相较||比较严谨, 当值等于 0 的时候 || 就把他给排除了,但是 ?? 不会
console.log(null || 1) // 1
console.log(null ?? 1) // 1
console.log(undefined || 1) // 1
console.log(undefined ?? 1) // 1
console.log(0 || 1) // 1
console.log(0 ?? 1) // 0
// 在 TypeScript 中联合类型(Union Types)表示取值可以为多种类型中的⼀种,联合类型使⽤ | 分隔每个类型。联合类型通常与 null 或 undefined ⼀起使⽤
const fn = (info: strong | null | undefined) => {}
四、?? 和 !! 示例代码
const foo = null ?? 'default string';
console.log(foo); // 输出: "default string"
const baz = 0 ?? 42;
console.log(baz); // 输出: 0
// 比如要赋值判断一个对象是否存在可以写成
let is_valid = (test)?true:false;
// 但是还有个更加简单的写法,!! 用于类型判断,在 ! 之后取反
// ! 变量后使用表示类型推断排除 null、 undefined,告诉TS此处一定有值
let is_valid = !!test;
console.log(!(0 + 0)) // 输出: true
console.log(!!(0 + 0)) // 输出: false
console.log(!!(3 * 3)) // 输出: true
更多推荐


所有评论(0)