ts里面的 ! 和 ? 还有 as以及各种符号的意义以及使用

https://www.jianshu.com/p/dd304d5cb3dc

  • 类型断言---as
    把一个大的范围断言成小的、精确的范围
type Method = 'GET' | 'POST'
function dd(url: string, method: Method) {
    console.log('lll');

};
let option = {
    url: 'https:',
    method: 'POST'
}
// dd(option.url, option.method)第二个参数会报错的,因为option.method的值是个字符串类型,而不是自己定义的Method类型
//可以用类型断言 as 因为string类型是大的范围,缩小到'POST'和'GET'这种小范围的类型
dd(option.url, option.method as Method)


//当然也可以给option定义一个类型
type getOption = {
    url: string,
    method: Method
}
let option:getOption  = {
    url: 'https:',
    method: 'POST'
}
dd(option.url, option.method)
  • 非空类型断言----!
    表示确定某个标识符是有值的,跳过ts在编译阶段对它的检测
function aa(value?:string){
    //加上 ! 的意思是确保value一定是有值的
    console.log(value!.length);
}
aa('ppp');

  • 可选链操作符----?.
    它的作用是当对象的属性不存在时,会短路,直接返回undefined,如果存在,那么才会继续执行。
type person = {
    name: string,
    age: number,
    friend?: {
        name: string,
        age?: number
    }
}
let p: person = {
    name: '张三',
    age: 10,
}
console.log(p.friend?.name);
  • ?? 和 !!的作用
    !! 将一个其他类型转换成boolean类型,类似于Boolean()
    ?? 空值合并操作符,当操作符的左侧是null或者undefined时,返回其右侧操作数,否则返回左侧操作数
let ss:string|null|undefined=undefined;
console.log(ss??'你好');
//ss??'你好' 可以给ss添加默认值 '你好' 意思就是如果 ss有值而且不是null和undefined时,ss就是上面赋给的值,如果是null或者undefined,ss的值就是默认值'你好'
posted @ 2021-12-29 15:23  最爱宋人头  阅读(6790)  评论(0编辑  收藏  举报