TypeScript 4.0 Beta 已釋出,整體看來,此版本在相容性方面沒有特別大的變化。因為 TypeScript 團隊表示新版本繼續使用與過去版本相似的版本控制模型,可將 4.0 視作 3.9 的延續升級版本。而且他們也一直在追求不犧牲主要靈活性的情況下,提供一個最大限度減少 breaking changes 的升級路徑。
可透過 NuGet 或在 npm 中使用以下命令進行 Beta 版的測試:
npm install typescript@beta
4.0 主要新功能
catch
子句中的unknown
--noEmitOnError
引數build
模式下的速度提升--incremental
with --noEmit
建構函式的類屬性推斷
當 noImplicitAny 被啟用時,TypeScript 4.0 現在可以使用控制流分(control flow analysis)析來確定類中的屬性型別。
class Square {
// Previously: implicit any!
// Now: inferred to `number`!
area;
sideLength;
constructor(sideLength: number) {
this.sideLength = sideLength;
this.area = sideLength ** 2;
}
}
如果並非將建構函式的所有路徑都分配給例項成員,則該屬性可能被視為undefined
。
class Square {
sideLength;
constructor(sideLength: number) {
if (Math.random()) {
this.sideLength = sideLength;
}
}
get area() {
return this.sideLength ** 2;
// ~~~~~~~~~~~~~~~
// error! Object is possibly 'undefined'.
}
}
在更清楚的情況下(例如具有某種initialize
方法),如果位於strictPropertyInitialization
中,可能會需要顯式型別註釋以及定值賦值斷言(!
)
class Square {
// definite assignment assertion
// v
sideLength!: number;
// ^^^^^^^^
// type annotation
constructor(sideLength: number) {
this.initialize(sideLength)
}
initialize(sideLength: number) {
this.sideLength = sideLength;
}
get area() {
return this.sideLength ** 2;
}
}
短路分配運算子
JavaScript 和其他很多語言都支援複合賦值運算子。複合賦值運算子將一個運算子應用到兩個引數上,然後將結果賦值到左邊。如下:
/ Addition
// a = a + b
a += b;
// Subtraction
// a = a - b
a -= b;
// Multiplication
// a = a * b
a *= b;
// Division
// a = a / b
a /= b;
// Exponentiation
// a = a ** b
a **= b;
// Left Bit Shift
// a = a << b
a <<= b;
JavaScript 中的許多運算子都有一個對應的賦值運算子,但有三個例外:邏輯和(&&
)、邏輯或(||
),以及空值合併(??
)。
TypeScript 4.0 為上述三個運算子增加了對應的賦值運算子支援:
let values: string[];
// Before
(values ?? (values = [])).push("hello");
// After
(values ??= []).push("hello");
a ||= b;
// actually equivalent to
a || (a = b);
[admin
]