billc.cn
billc.cn

Reputation: 7317

TypeScript operator precedence table (or what's the precedence of Type Assertions?)

I guess operators exist in JavaScript use their original precedence, but new constructs like Type Assertions (i.e. <Type> expr) and arrow function expressions are less clear.

It will be helpful if there's an official table somewhere.

Upvotes: 7

Views: 2109

Answers (1)

Fenton
Fenton

Reputation: 250922

I have supplied some examples of Type Assertions below that will hopefully shine some light on this feature for you.

The interesting bit is that if a set of parentheses has an affect on the scope of a type assertion, the parentheses are removed by type erasure during compilation. This means that example b below results in (x) in the JavaScript, whereas example c results in simply x.

The only reason to use parentheses to set the scope of the type assertion is when you want to apply to a part of the right-hand expression, in which case you would place the type assertion inside of the parentheses, as shown in example e.

interface SomeType {
    name: string;
    id: number;
}

var x = {};

var a: SomeType = <SomeType> x;

// Note, when brackets do not affect 
// type assertions they will be left in the output
var b: SomeType = <SomeType> (x);

// When brackets affect type assertions,
// they are erased along with the type information
var c: SomeType = (<SomeType> x);

// Two errors:
// - SomeType is not assignable to d
// - Property id does not exist on x
var d: number = <SomeType> x.id;

// Brackets are useful here:
var e: number = (<SomeType> x).id;

// More complex example
var func = () => {
    return x; // return type is {}
};
var f: SomeType = <SomeType> func();

Upvotes: 3

Related Questions