有什麼之間的打字稿規範要求一個類型斷言任何區別:TypeScript中的類型斷言和更新的`as`運算符之間的任何區別?
var circle = <Circle> createShape("circle");
而且neweras
操作:
var circle = createShape("circle") as Circle;
這兩者通常用於編譯時鑄造?
有什麼之間的打字稿規範要求一個類型斷言任何區別:TypeScript中的類型斷言和更新的`as`運算符之間的任何區別?
var circle = <Circle> createShape("circle");
而且neweras
操作:
var circle = createShape("circle") as Circle;
這兩者通常用於編譯時鑄造?
區別在於as Circle
適用於TSX文件,但<Circle>
與JSX語法衝突。爲此推出了as
。
例如,在一個.tsx
文件下面的代碼:
var circle = <Circle> createShape("circle");
將導致以下錯誤:
error TS17002: Expected corresponding JSX closing tag for 'Circle'.
然而,as Circle
會工作得很好。
從現在開始使用as Circle
。這是推薦的語法。
從Wiki page: 「什麼打字稿[1.6]最新消息」:
New
.tsx
file extension andas
operatorTypeScript 1.6 introduces a new
.tsx
file extension. This extension does two things: it enables JSX inside of TypeScript files, and it makes the newas
operator the default way to cast (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator). For example:var x = <any> foo; // is equivalent to: var x = foo as any;