【问题标题】:why ?? is not working with ternary operatorwhy ?? is not working with ternary operator
【发布时间】:2022-11-20 20:26:42
【问题描述】:

why Null Coalescing is not working with ternary operator. I would expect to get tdy.

const test = {
  todo: {
    day: 'tdy'
  }
}

const filterDayRange = [{
    day: 'mon'
}]

 const result =
      test.todo?.day ?? filterDayRange.length > 0 ? filterDayRange[0].day : 'tdy';

console.log(result)


// expected Output: tdy

Playground link

【问题讨论】:

    标签: typescript


    【解决方案1】:

    I simply add Parantheses :

     test.todo?.day ?? (filterDayRange.length > 0 ? filterDayRange[0].day : 'tdy');
    

    and now it works fine

    【讨论】:

      【解决方案2】:

      Everythings seems to work as expected. filterDayRange.length > 0 evaluates to truth. You can test it by replacing the result expressions in ternary operator

      const test  = {
        todo: { 
          day: 'tdy'
        }
      }
      
      const filterDayRange = [{
          day: 'mon'
      }]
      
       const result =
            test.todo?.day ?? filterDayRange.length > 0 ? 'tdy': filterDayRange[0].day;
      
      console.log(result)
      

      【讨论】:

        【解决方案3】:

        separate the ternary operator will fix the issue

        let result = test.todo?.day ?? (filterDayRange.length > 0 ? filterDayRange[0].day : 'tdy')
        

        【讨论】:

          猜你喜欢
          • 2022-12-02
          • 2022-12-02
          • 2017-09-22
          • 1970-01-01
          • 2022-12-26
          • 1970-01-01
          • 2022-01-03
          • 2022-11-20
          • 1970-01-01
          相关资源
          最近更新 更多