打字稿类型断言运算符优先级

时间:2021-07-29 12:20:14

标签: javascript typescript logical-operators operator-precedence

我应该将 js-ternary 运算符包装在 'as' 类型断言上吗?

ios ? TouchableOpacity : View as React.ElementType

或者,因为它总是“先来”,它会使用“?:”结果?

或更好的实施将:

(ios ? TouchableOpacity : View) as React.ElementType

1 个答案:

答案 0 :(得分:1)

a ? b : c as T 等价于 a ? b : (c as T)

Here's a little demo of the difference

Math.random() > .5 ? '' : 0 as string
//                        ~~~~~~~~~~~
// Conversion of type 'number' to type 'string' may be a mistake...

// Ok
(Math.random() > .5 ? '' : 0) as string