ts中的?、??、!、!!
下面是?、??、!、!!的基本介绍:
- 属性或参数中使用?表示该属性或参数为可选项
- ??表示只有当左侧为null和undefined时, 才会返回右侧的数
- 属性或参数中使用!表示表示强制解析(告诉typescript编译器,这里一定有值)
- 变量前使用!表示取反, 变量后使用!表示类型推断排除null、undefined从而使null 和undefined类型可以赋值给其他类型并通过编译
- !!表示将把表达式强行转换为逻辑值
?相关代码
当使用A对象属性A.B时,如果无法确定A是否为空,则需要用A?.B,表示当A有值的时候才去访问B属性,没有值的时候就不去访问,如果不使用?则会报错
const user = null;
console.log(user.account) // 报错
console.log(user?.account) // undefined
另外一种解释:?.允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?.操作符的功能类似于.链式操作符,不同之处在于,在引用为空(null 或者 undefined)的情况下不会引起错误而是直接返回null or undefined
?:是指可选参数,可以理解为参数自动加上undefined
export interface RequestForm{
pageSize : number
pageNumber : number
name?:string // 可选属性
sex ?:string // 可选属性
}
?? 和 || 的意思有点相似,但是又有点区别,??相较||比较严谨, 当值等于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
!.的意思是断言,告诉ts你这个对象里一定有某个值
const inputRef = useRef<HTMLEInputlement>(null);
// 定义了输入框,初始化是null,但是你在调用他的时候相取输入框的value,这时候dom实例一定是有值的,所以用断言
const value: string = inputRef.current!.value;
// 这样就不会报错了
!相关代码
!的示例代码如下:
erface IDemo {
x?: number
}
const demo = (parma: IDemo) => {
const y:number = parma.x! // 变量值可空, 当x为空时将返回undefined
return y
}
console.log(demo({})) // 输出: undefined
console.log(demo({x: 3})) // 输出: 3
??和!!示例代码
const foo = null ?? 'default string';
console.log(foo); // 输出: "default string"
const baz = 0 ?? 42;
console.log(baz); // 输出: 0
比如要赋值判断一个对象是否存在可以写成
let is_valid = (test)?true:false;
但是还有个更加简单的写法
let is_valid = !!test;
console.log(!!(0 + 0)) // 输出: false
console.log(!!(3 * 3)) // 输出: true