ts中的特殊符号 ?. ?: 等代表的含义与使用

前言:

        ts相比较js来说,是比较严格的,他中间新增了很多可选链符号,比如:?. ?: !.

1、?:     是指可选参数,定义对象属性时候,或者参数接收时可用

注:如果没有属性,则表示  undefined

项目中具体使用:

 vue3中使用:

const {icon,size }= defineProps<{  // 通过 TS的泛型  定义接收的数据类型
    icon:any,
    size?:number|string, // size 可选参数,类型为 字符串或数值
}>()

2、?.    意思基本和 && 是一样的,如果用在对象的属性里面的话,表示对象和对象里属性都需要

比如:a?.b 相当于 a && a.b ? a.b : undefined

项目中具体使用:

//等同于  config.interceptors && config.interceptors.requestInterceptor
if (config.interceptors?.requestInterceptor) {
    config = config.interceptors.requestInterceptor(config)
}

 3、!.   的意思是  断言,告诉ts你这个对象里一定有某个值

注:一般是防止报错使用

项目中具体使用:

const inputRef = useRef<HTMLEInputlement>(null);
// 定义了输入框,初始化是null,但是你在调用他的时候相取输入框的value,
这时候dom实例一定是有值的,所以用断言
const value: string = inputRef.current!.value;
// 这样就不会报错了

4、??  和 || 的意思有点相似

注:??相较||比较严谨, 当值等于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

到此结束!

猜你喜欢

转载自blog.csdn.net/qq_41619796/article/details/129833416