使用 Optional Chaining 和 Nullish Coalescing Operator

4,621 阅读2分钟

你一定有这样的问题。


const fetchUser = () => {
    return {
        name: 'hello world',
        gender: 'male'
    }
}

const user = fetchUser()

console.log(user.name)

// => hello word
  
  • 但是结果并不如人意

const fetchUser = () => {
    return null
}

const user = fetchUser()

console.log(user.name)
  
// /(ㄒoㄒ)/~~
// => Uncaught TypeError: Cannot read property 'name' of null
  
  • 于是你学会了面向搜索引擎编程,打开了 bai**.com, goo**.com, bi**.com

const fetchUser = () => {
    return null
}

const user = fetchUser()

console.log(user && user.name)
  
// 终于解决了
// => null
  
  • 直到,你遇见了ta...

const fetchUser = () => {
    return {
        name: 'hello world',
        gender: 'male',
        children: [
            {
                name: 'hi, my son',
                gender: 'male',
                children: [
                    {
                        name: 'hi, my grandson 😭',
                        gender: 'male',
                    }
                ]
            }
        ]
    }
}

const user = fetchUser()

console.log(user && 
            user.children && 
            user.children[0] && 
            user.children[0].children &&
            user.children[0].children[0] &&
            user.children[0].children[0].name)
  
// 太难了 😭😭😭😭
// => hi, my grandson 😭
  

是时候使用 Optional Chaining 了

什么是 optional chaining

  • Optional 可选链,核心作用是允许读取一个被连接对象的深层次的属性的值而无需明确校验链条上每一个引用的有效性

  • Optional 使用 ?. 作为操作符

  • Optional 处于 Stage 3 阶段,但目前已有 babel 支持。

  • 它不是编程语言的新特性,在其它语言早有实现。

    • C#

      
      Object object;
      
      object?.prop1?.prop2?.prop3 ?? "default";
      
      
    • Java

      
      Object object;
      
      Optional.ofNullable(object)
          .map(obj -> obj.prop1)
          .map(obj -> obj.prop2)
          .map(obj -> obj.prop3)
          .orElse("default");
      
      

如何使用 optional chaining

要注意的是,目前尚无浏览器支持 optional chaining,需要使用 babel 转义。

  1. 添加 @babel/babel-plugin-proposal-optional-chaining

    npm install @babel/plugin-proposal-optional-chaining --D
    

    or

    yarn add @babel/plugin-proposal-optional-chaining -D
    
  2. 添加 @babel/plugin-proposal-nullish-coalescing-operator

    npm install @babel/plugin-proposal-nullish-coalescing-operator --D
    

    or

    yarn add @babel/plugin-proposal-nullish-coalescing-operator -D
    
  3. 修改 .babelrc

    {
        "plugins": [
            "@babel/plugin-proposal-optional-chaining",
            "@babel/plugin-proposal-nullish-coalescing-operator"
        ]
    }
    

开始愉快玩耍

  1. 使用 optional chaining

    const user = {
        name: 'hello,world',
        gender: 'male'
    }
    
    console.log(user?.children?.name)
    // => undefined
    console.log(user?.name)
    // => hello,world
    
  2. 使用 optional chaining 和 nullish

    const user = {
        name: 'hello,world',
        gender: 'male'
    }
    
    console.log(user?.children?.children?.children ?? '未定义')
    
    // => 未定义
    
  3. 结合数组,对象和 nullish

    
    const fetchUser = () => {
        return {
            name: 'hello world',
            gender: 'male',
            children: [
                {
                    name: 'hi, my son',
                    gender: 'male',
                    children: [
                        {
                            name: 'hi, my grandson 😀',
                            gender: 'male',
                        }
                    ]
                }
            ]
        }
    }
    
    const user = fetchUser()
    
    console.log(user?.children?.[0]?.children?.[0]?.name ?? '未定义')
      
    // => hi, my grandson 😀
      
    

参考