6

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.

billc.cn
  • 7,187
  • 3
  • 39
  • 79
  • The specification contains information on how certain amiguities are resolved. – Ingo Bürk Feb 03 '15 at 16:22
  • @IngoBürk I have read the spec, but it is not very clear to me how type assertions interact with property access and function expressions. E.g., what does this expression mean ` a.b`? – billc.cn Feb 03 '15 at 17:26
  • 1
    4.13 states that type assertions are applied on an (entire) unary expression. Hence, I would expect that ` a.b` is equivalent to ` (a.b)`. And a quick test does confirm this. – Ingo Bürk Feb 03 '15 at 17:42

1 Answers1

3

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();
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • Okay, so it matches the cast operator in C-like languages. However, I just want to point out another thing: function application binds more closely than type assertion, so the following does not type: `interface FunType { (): string } var x: string= function() {return undefined;}();`. This again matches C, but is unclear solely based on the spec. – billc.cn Feb 04 '15 at 09:40