Search code examples
javascripttypescriptlogical-operatorsoperator-precedence

Typescript Type Assertion operator precendence


Should i wrap js-ternary operator on 'as' Type Assertion?

ios ? TouchableOpacity : View as React.ElementType

or, as it always 'comes first' it will use '?:' result?

or better implementation will:

(ios ? TouchableOpacity : View) as React.ElementType

Solution

  • a ? b : c as T is equivalent to 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