TypeScript运算符优先级表(或类型断言的优先级是什么?)

时间:2015-02-03 16:18:20

标签: typescript

我猜JavaScript中的运算符使用它们的原始优先级,但是像Type Assertions(即<Type> expr)和箭头函数表达式这样的新结构不太清楚。

如果在某个地方有官方表格会有所帮助。

1 个答案:

答案 0 :(得分:1)

我在下面提供了一些类型断言的示例,希望能为您提供一些有关此功能的信息。

有趣的是,如果一组括号对类型断言的范围有影响,则在编译期间通过类型擦除删除括号。这意味着下面的示例b会在JavaScript中生成(x),而示例c只会导致x

使用括号设置类型断言范围的唯一原因是当您要应用于右侧表达式的一部分时,在这种情况下,您可以将类型断言放在括号内,如下所示例如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();
相关问题