我猜想 JavaScript 中存在的运算符使用其原始优先级,但像类型断言(即<Type> expr)和箭头函数表达式这样的新结构不太清晰。
如果某个地方有正式的桌子会很有帮助。
我在下面提供了一些类型断言的示例,希望能为您阐明此功能。
有趣的是,如果一组括号对类型断言的范围有影响,则在编译期间通过类型擦除来删除括号。这意味着b下面的示例会生成(x)JavaScript,而示例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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1984 次 |
| 最近记录: |