本文爲公衆號「TypeScript社區(QQ 羣號 390037547)」原創翻譯,轉載請註明出處!不然追究法律責任!node
TypeScript 3.2 正式版於 2018 年 11 月 29 日發佈。此版本新增特性及變動事項以下:redis
• 嚴格的 bind、call 和 apply
• 泛型類型上的對象展開操做
• 泛型類型上的對象剩餘操做
• 基於 Node.js 的 tsconfig.json 繼承解決方案
• 使用「--showConfig」來對 tsconfig.json 進行診斷
• BigInt
• JavaScript 中的 Object.defineProperty 聲明
• 錯誤信息改進
• 標記化聯合類型的類型收窄改進
• 編輯改進
• 破壞性變動和棄用項
• NuGet 和 Visual Studio 2015 用戶注意事項
• 下一步是什麼typescript
下面爲你們帶來 TypeScript 官方博客的翻譯:
TypeScript 3.2 is here today!
今天 TypeScript 3.2 到來了!
If you’re unfamiliar withTypeScript, it’s a language that brings static type-checking to JavaScript so that you can catch issues before you even run your code – or before you even save your file. It also includes the latest JavaScript features from the ECMAScript standard on older browsers and runtimes by compiling those features into a form that they understand. But beyond type-checking and compiling your code, TypeScript also provides tooling in your favorite editor so that you can jump to the definition of any variable, find who’s using a given function, and automate refactorings and fixes to common problems. TypeScript even provides this for JavaScript users (and can also type-check JavaScript code typed withJSDoc), so if you’ve used editors like Visual Studio or Visual Studio Code on a .js file, TypeScript is powering that experience.
若是你不熟悉 TypeScript,它是一門語言,爲JavaScript 帶來了靜態類型檢查以便你可以在運行代碼前甚至是保存文件前捕獲問題。它還包括來自 ECMAScript 標準的最新的 JavaScript 特性,這些特性可以運行在老版本的瀏覽器或運行時上——經過將這些新特性編譯爲老版本瀏覽器或運行時理解的形式來實現。可是,除了類型檢查和編譯你的代碼,TypeScript 還提供了你最喜歡的編輯器中的工具以便你能夠跳轉到任何變量的定義位置,找到誰正在使用某個函數,以及自動地重構和修復常見的問題。TypeScript 甚至爲 JavaScript用戶提供了這些功能特性(也能夠對使用 JSDoc類型化後的 JavaScript 代碼進行類型檢查),因此若是你使用如 Visual Studio 或者 Visual Studio Code 這樣的編輯器來編輯 js 文件,TypeScript 正在爲這些體驗提供動力。
To get started with the language itself, check out typescriptlang.org to learn more.
要開始使用這個語言,請查看這裏typescriptlang.org 以瞭解更多信息。
But if you want to try TypeScript 3.2 out now, you can get it through NuGet or via npm by running
可是若是你想要如今就嘗試 TypeScript 3.2,你能夠經過 NuGet 或者經過npm(經過運行如下命令)來獲取它:
npm install -g typescript
You can also get editor support for
你也能夠得到對如下編輯器的支持:
• Visual Studio 2017 (for version 15.2 or later).
Visual Studio 2017(版本 15.2 或更高版本)。
• Visual Studio 2015 (which requires update 3).
Visual Studio 2015(須要更新版 3)。
• For Visual Studio Code by installing the Insiders release until the full release provides it.
對於 Visual Studio Code,在提供完整發布版以前經過安裝預覽發佈版來獲取。
• Sublime Text 3 via PackageControl.
Sublime Text 3 經過 PackageControl 獲取。
Other editors may have different update schedules, but should all have TypeScript available soon.
其它編輯器會有不一樣的更新計劃,但都會很快就有可用的 TypeScript。
We have some important information below for NuGet users and Visual Studio 2015 users, so please continue reading if you use either product.
下面咱們有一些對 NuGet 和 Visual Studio 2015用戶而言很是重要的信息,因此若是你使用這兩個產品,請繼續閱讀。
Below we have a bit about what’s new in 3.2.
下面是關於 3.2 中新增的內容。
• strictBindCallApply
嚴格的 bind、call 和 apply
• Object spread on generic types
泛型類型上的對象展開
• Object rest on generic types
泛型類型上的對象剩餘操做
• Node.js-based resolution for tsconfig.json inheritance
基於 Node.js 的 tsconfig.json 繼承解決方案
• Diagnosing tsconfig.json with --showConfig
使用「--showConfig」來對 tsconfig.json 進行診斷
• BigInt
大整數
• Object.defineProperty declarations in JavaScript
JavaScript 中的 Object.defineProperty 聲明
• Error message improvements
錯誤信息改進
• Improved narrowing for tagged unions
標記式聯合類型的類型收窄改進
• Editing improvements
編輯改進
• Breaking changes and deprecations
破壞性變動和棄用項
A note for NuGet and Visual Studio 2015 users
給 NuGet 和 VisualStudio 2015 用戶的提示
• What’s next
下一步是什麼
strictBindCallApply
嚴格的 bind、call 和 apply
As you might’ve guessed from the title of this section, TypeScript 3.2 introduces stricter checking for bind, call, and apply. But what does that mean?
正如你可能從這個標題所猜想的那樣,TypeScript3.2 引入了對 bind、call 和 apply 更嚴格的檢查。但那意味着什麼呢?
Well, in JavaScript, bind, call, and apply are methods on functions that allow us to do things like bind this and partially apply arguments, call functions with a different value for this, and call functions with an array for their arguments.
在 JavaScript 中,bind、call 和 apply 是在函數上的方法,它們容許咱們作這些事情——綁定 this並應用部分參數,使用一個不一樣的 this 值來調用函數,以及使用承載函數參數的數組來調用函數。
Unfortunately, in its earlier days, TypeScript lacked the power to model these functions, and bind, call, and apply were all typed to take any number of arguments and returned any. Additionally, ES2015’s arrow functions and rest/spread arguments gave us a new syntax that made it easier to express what some of these methods do – and in a more efficient way as well.
不幸的是,在早些時期,TypeScript 缺乏對這些函數建模的能力,而且 bind、call 和 apply 都被類型化爲接收任意數量的參數並返回 any 的函數。另外,ES2015 的箭頭函數和剩餘/展開參數帶給咱們一個新的語法,它使得表達這些方法是作什麼的變得更容易也更高效。
Still, demand to model these patterns in a type-safe way led us to revisit this problem recently. We realized that two features opened up the right abstractions to accurately type bind, call,and apply without any hard-coding:
儘管如此,要求以類型安全的方式對這些模式進行建模,使得咱們最近又從新審視了這個問題。咱們意識到兩個特性開闢了正確的抽象來精確地標註 bind、call 和 apply 的類型而無需任何硬編碼:express
來自 TypeScript 2.0 的 this 參數類型npm
來自 TypeScript 3.0 的使用元組類型模擬參數列表
Combined, the two of of them can ensure our uses of bind, call, and apply are more strictly checked when we use a new flag called strictBindCallApply. When using this new flag,the methods on callable objects are described by a new global type called CallableFunction which declares stricter versions of the signatures for bind, call,and apply. Similarly, any methods on constructable (but not callable) objects are described by a new global type called NewableFunction.
結合起來,當咱們使用一個新的稱做 strictBindCallApply 的標誌時,這兩項可以確保咱們對 bind、call 和 apply 的使用可以被嚴格地檢查。當使用這個新標誌時,可調用地對象上的方法被一個被稱爲 CallableFunction 的全局類型所描述,該類型聲明瞭 bind、call 和 apply 簽名的更嚴格的版本。相似的,可構建(但不是可調用)對象上的任何方法都是被一個被稱爲 NewableFunction 的全局類型所描述。
As an example, we can look at how Function.prototype.apply acts under this behavior:
做爲例子,咱們能夠看到在這個行爲之下 Function.prototype.apply 是如何表現的:
function foo(a:number, b:string):string{
return a + b;
}編程
let a = foo.apply(undefined, [10]);// error: too few argumnts
let b = foo.apply(undefined, [10, 20]);// error: 2nd argument is anumber
let c = foo.apply(undefined,[10, "hello", 30]); // error: too many arguments
let d = foo.apply(undefined,[10, "hello"]);// okay! returns a string
Needless to say, whether you do any sophisticated metaprogramming, or you use simplepatterns like binding methods in your class instances (this.foo=this.foo.bind(this)), this feature can help catch a lot of bugs. For more details, you can check out the original pull request here.
不用說,不管你是作複雜的元編程,或者是使用簡單的模式,如在類實例裏綁定方法(如 this.foo = this.foo.bind(this)),這個特性能夠幫助捕獲許多的 bug。更多詳細信息,你能夠在這裏查看原始的拉取請求。
Caveats
注意事項
One caveat of this new functionality is that due to certain limitations, bind, call, and apply can’t yet fully model generic functions or functions that have overloads.When using these methods on a generic function, type parameters will be substituted with the empty object type ({}), and when used on a function with overloads, only the last overload will ever be modeled.
這個新功能特性有一點須要注意的是,由於某些限制,bind、call 和 apply 不能徹底地對泛型函數或者重載函數進行建模。當在一個泛型函數上使用這些方法時,類型參數將會被空對象({})替代,而當在一個重載函數上使用時,只對最後一個重載進行建模。
Objects pread on generic types
泛型類型上的對象展開
JavaScript supports a handy way of copying existing properties from an existing object into a new one called 「spreads」. To spread an existing object into a new object, you define an element with three consecutive periods (...) like so:
JavaScript支持一種簡便的方式來從一個現有的對象上覆制屬性到一個新的對象中,這種方式叫作「展開」。要將一個現有對象展開到一個新的對象中,你要定義一個這樣帶三個連續句點(...)的元素:
let person = { name:"Daniel", location:"New York City"};json
// My secret revealed, I have two clones!
let shallowCopyOfPerson = { ...person };
let shallowCopyOfPersonWithDifferentLocation = {...person, location:"Seattle"};
TypeScript does a pretty good job here when it has enough information about the type. The type system closely tries to model the behavior of spreads and overwrites new properties, tries to ignore methods, etc. But unfortunately up until now it wouldn’t work with generics at all.
當有足夠多的關於類型的信息時,TypeScript 能工做得很好。類型系統嘗試模擬展開行爲並覆寫新的屬性,嘗試忽略方法等。但不幸的是,直到目前它仍徹底沒法用於泛型。
function merge<T,U>(x: T,y:U) {
// Previously an error!
return { ...x, ...y };
}
This was an error because we had no way to express the return type of merge. There was no syntax (nor semantics) that could express two unknown types being spread into a new one.
這曾經是一個錯誤由於咱們沒法表示 merge 的返回類型。沒有語法(或者語義)可以表示兩個未知類型展開到一個新的類型中。
We could have come up with a new concept in the type system called an 「object spread type」, and in fact we had a proposal for exactly that. Essentially this would be a new type operator that looks like { ...T,...U } to reflect the syntax of an object spread.
咱們可能會想出一個新的概念,在類型系統中稱爲「對象展開類型」,事實上咱們的確有那麼個提案。實質上,它會成爲一個新的,看起來像「{...T,...U }」 這樣的類型操做符以反映一個對象展開的語法。
When both T and U are known, that type would flatten down to some new object type.
當T 和 U 都是未知的時候,那個類型將會扁化爲某些新的對象類型。
However, this is pretty complex and requires adding new rules to type relationships and inference. While we explored several different avenues, we recently arrived at two conclusions:
然而,這是至關複雜的,且須要添加新的規則到類型關係和推斷中。當咱們考察了幾種不一樣的方式後,咱們最近獲得兩個結論:數組
JavaScript中使用的大多數展開,用戶可使用交叉類型(例如 Foo& Bar)來模擬該行爲。瀏覽器
Object.assign——一個展現了展開對象的絕大多數行爲的函數——已經使用交叉類型進行模擬,而且咱們未看到關於它的負面反饋。
Given that intersections model the common cases, and that they’re relatively easy to reason about for both users and the type system, TypeScript 3.2 now permits object spreads on generics and models them using intersections:
鑑於交叉類型模擬了常見的情形,且對於用戶和類型系統而言相對容易推理,TypeScript 3.2 如今容許對泛型進行對象展開並使用交叉類型來模擬它們:
// Returns 'T & U'
function merge<T,U>(x:T, y:U) {
return{ ...x, ...y };
}安全
// Returns '{ name: string, age: number,greeting: string } & T'
function foo<T>(obj:T) {
let person = {
name: "Daniel", age:26
};
return { ...person, greeting:"hello", ...obj };
}
Object rest on generic types
泛型類型上的對象剩餘操做
Object rest patterns aresort of the dual of object spreads. Instead of creating a new object with some extra/overridden properties, it creates a new object that lacks some specified properties.
對象剩餘模式有點像雙重的對象展開。它建立一個新的缺乏某些特定屬性的對象,而不是建立一個新的帶有額外的/被覆蓋的屬性的對象。
let { x, y, z, ...rest } = obj;
In the above, the most intuitive way to look at this code is that rest copies over all the properties from obj apart from x, y, and z. For the same reason as above, because we didn’t have a good way to describe the type of rest when obj is generic, we didn’t support this for a while.
如上,最直觀的看待這個代碼的方式是 rest 從 obj 複製除了 x、y 和 z 以外的全部屬性。因爲上述相同的緣由,當 obj 是泛型時,咱們沒有一個好的方式來描述 rest 的類型,咱們暫時不支持這個。
Here we also considered a new rest operator, but we saw we already had the facilities for describing the above: our Pick and Exclude helper types in lib.d.ts To reiterate, ...rest basically picks off all ofthe properties on obj except for x, y, and z in the following example:
這裏咱們也考慮過一個新的剩餘運算符,但咱們看到咱們已經有了描述上述情形的裝備:lib.d.ts 中的 Pick 和 Exclude 幫助器類型。爲了重申這一點,下面例子中 ...rest 拾取 obj 中除了 x、y 和 z 的全部屬性:
interface XYZ{ x:any; y:any; z:any; }
function dropXYZ<T extends XYZ>(obj:T) {
let { x, y, z, ...rest } = obj;
return rest;
}
If we want to consider the properties of T (i.e. keyof T) except for x, y, and z, we can write Exclude<keyof T, "x" | "y" | "z">. We then want to pick those properties back off of the original type T, which gives us
若是咱們要考慮 T(例如,keyof T)中除了 x、y 和 z 以外的屬性,咱們能夠寫 Exclude<keyof T, "x" | "y" |"z">。咱們而後想要把原來的那個類型 T 的那些屬性取回來,這讓我獲得:
Pick<T, Exclude<keyof T, "x" |"y" | "z">>`.
While it’s not the most beautiful type (hey, I’m no George Clooney myself), we can wrap it in a helper type like DropXYZ:
雖然它不是最好看的類型,咱們能夠把它包裝到一個幫助器類型中,如 DropXYZ:
interface XYZ { x:any; y:any; z:any; }
type DropXYZ<T> = Pick<T, Exclude<keyof T, keyof XYZ>>;
function dropXYZ<T extends XYZ>(obj:T):DropXYZ<T> {
let { x, y, z, ...rest } = obj;
return rest;
}
Configuration inheritance via node_modules packages
經過 node_modules 包實現配置繼承
For a long time TypeScript has supported extending tsconfig.json files using the extends field.
很早之前 TypeScript 就已經支持使用 extends 字段來擴展 tsconfig.json 文件。
{
"extends":"../tsconfig-base.json",
"include": ["./*/"]
"compilerOptions": {
// Override certain options on a project-by-projectbasis. "strictBindCallApply":false,
}
}
This feature is very useful to avoid duplicating configuration which can easiy fall out of sync, but it really works best when multiple projects are co-located in the same respository so that each project can reference a common 「base」 tsconfig.json.
這個特性對於避免重複配置是很是有用的,這些重複的配置很容易失去同步,可是當多個項目共同位於同一個儲存庫中時,它確實是最有效的,這樣每一個項目均可以引用一個通用的基礎 tsconfig.json。
But for some teams, projects are written and published as completely independent packages. Those projects don’t have a common file they can reference, so as a workaround, users could create a separate package and reference that:
可是對於某些團隊,項目是做爲徹底獨立的包來編寫和發佈的。那些項目沒有一個通用的文件能夠供他們引用,所以,做爲一個變通方案,用戶能夠建立一個單獨的包並引用它:
{
"extends": "../node_modules/@my-team/tsconfig-base/tsconfig.json",
"include": ["./*/"]
"compilerOptions": {
// Override certain options on a project-by-projectbasis. "strictBindCallApply":false, }
}
However,climbing up parent directories with a series of leading ../s and reaching directly into node_modules to grab a specific file feels unwieldy.
然而,經過一系列前導的 ../ 爬升到父目錄並進入到 node_modules 來獲取特定的文件顯得很粗笨。
TypeScript 3.2 now resolves tsconfig.jsons from node_modules. When using a bare path for the "extends" field in tsconfig.json,TypeScript will dive into node_modules packages for us.
TypeScript 3.2 如今從 node_modules 中解析 tsconfig.json。當在 tsconfig.json 中爲「extends」字段使用一個裸路徑(沒有前導的「../」)時,TypeScript 將會爲咱們潛入到 node_modules 包中。
{
"extends":"@my-team/tsconfig-base",
"include": ["./*/"]
"compilerOptions": {
// Override certain options on a project-by-projectbasis. "strictBindCallApply":false,
}
}
Here,TypeScript will climb up node_modules folders looking for a @my-team/tsconfig-base package. For each of those packages, TypeScript will first check whether package.json contains a "tsconfig" field, and if it does,TypeScript will try to load a configuration file from that field. If neither exists, TypeScript will try to read from a tsconfig.json at the root. This is similar to the lookup process for .js files in packages that Node uses, and the .d.ts lookup process that TypeScript already uses.
在這裏,TypeScript 將會爬升到 node_modules 文件夾查找一個叫作 @my-team/tsconfig-base 的包。對於每個包,TypeScript 將會首先檢查 package.json 是否包含一個「tsconfig」字段,若是有,TypeScript 將會嘗試從根據那個字段加載配置文件。若是都沒有,TypeScript 將會嘗試從根目錄的 tsconfig.json 讀取。這和查找 Node 使用的 .js 文件的過程以及查找TypeScript 已經使用的 .d.ts 文件的過程類似。
This feature can be extremely useful for bigger organizations, or projects with lots of distributed dependencies.
這個特性對於大型組織或者有許多分佈式依賴的項目特別的有用。
Diagnosing tsconfig.json with --showConfig
使用 --showConfig 來診斷 tsconfig.json
tsc, the TypeScript compiler, supports a new flag called --showConfig. When running tsc --showConfig, TypeScript will calculate the effective tsconfig.json (after calculating options inherited from the extends field) and print that out.This can be useful for diagnosing configuration issues in general.
TypeScript 編譯器 tsc 支持新的稱做 --showConfig 的標誌。當運行 tsc --showConfig 時,TypeScript 將會計算有效的 tsconfig.json(在計算繼承於 extends 字段的選項以後)並把它們打印出來。通常這對於診斷配置問題頗有用。
BigInt
大整數
BigInts are part of an upcoming proposal in ECMAScript that allow us to model theoretically arbitrarily large integers. TypeScript 3.2 brings type-checking for BigInts, as well as support for emitting BigInt literals when targeting esnext.
BigInt 是即將到來的 ECMAScript提案中的一部分,它容許咱們模擬理論上任意大的整數。當將編譯目標設定爲 esnext 時,TypeScript3.2 爲BigInt 帶來了類型檢查以及支持生成 BigInt 字面量。
BigInt support in TypeScript introduces a new primitive type called the bigint (all lowercase). You can get a bigint by calling the BigInt() function or by writing out a BigInt literal by adding an n to the end of any integer numeric literal:
在 TypeScript 中支持 BigInt,引入了一個新的稱爲 bigint (所有小寫)的基本類型。你能夠經過調用 BigInt() 函數或者經過直接在任意整數字面量的後面加上一個 n 來書寫 BigInt 字面量而獲得一個 bigint。
let foo: bigint = BigInt(100);// the BigInt function
let bar:bigint = 100n; // a BigInt literal
// Slaps roof of fibonacci function
// This bad boy returns ints that can getso big!
function fibonacci(n:bigint) {
let result = 1n;
for (let last = 0n, i = 0n; i < n; i++) {
const current = result; result += last; last = current; }
return result;
}
fibonacci(10000n)
While you might imagine close interaction between number and bigint, the two are separate domains.
雖然你可能想要 number 和 bigint 之間緊密交互,但它們兩個屬於不一樣的領域。
declare let foo:number;
declare let bar:bigint;
foo = bar;// error: Type 'bigint' is not assignable to type 'number'.
bar = foo;// error: Type 'number' is not assignable to type 'bigint'.
As specified in ECMAScript, mixing numbers and bigints in arithmetic operations is an error. You’ll have to explicitly convert values to BigInts.
如在 ECMAScript 中規定的那樣,在算術運算中混合 number 和 bigint 是錯誤的。你將必須顯式地把值轉換爲 BigInt。
console.log(3.141592*10000n); //error
console.log(3145*10n); //error
console.log(BigInt(3145) *10n); //okay!
Also important to note is that bigints produce a new string when using the typeof operator: the string "bigint". Thus, TypeScript correctly narrows using typeof as you’d expect.
還須要關注的一點是,當對 BigInt 使用 typeof 運算符時將會產生一個新的字符串——「bigint」。所以,如你所期盼的那樣,TypeScript 正確地收窄了 typeof。
function whatKindOfNumberIsIt(x:number | bigint) {
if(typeof x === "bigint") {
console.log("'x' is a bigint!");
}
else{
console.log("'x' is a floating-point number"); }
}
We’d like to extend a huge thanks to CalebSander for all the work on this feature. We’re grateful for the contribution, and we’re sure our users are too!
咱們很是感謝 Caleb Sander 爲這個特性所作的全部工做。咱們很感謝這個貢獻,咱們也確信咱們的用戶也是如此!
Caveats
注意事項
As we mentioned, BigInt support is only available for the esnext target. It may not be obvious, but because BigInts have different behavior for mathematical operators like +, -, *,etc., providing functionality for older targets where the feature doesn’t exist (like es2017 and below) would involve rewriting each of these operations. TypeScript would need to dispatch to the correct behavior depending on the type, and so every addition, string concatenation,multiplication, etc. would involve a function call.
如咱們所提到的,BigInt 的支持僅對 esnext 做爲編譯目標時可用。它可能不明顯,可是由於BigInt 對於算術運行符如 +、-、 * 等有不一樣的行爲,爲那些不存在該特性的老版本目標(如 es2017 及如下版本)提供該功能將會涉及重寫這每個運算符。TypeScript 將須要依據類型調度正確的行爲,因此每個加法,字符串鏈接,乘法等,將會涉及到一個函數調用。
For that reason, we have no immediate plans to provide downleveling support. On the bright side, Node 11and newer versions of Chrome already support this feature, so you’ll be able touse BigInts there when targeting esnext.
鑑於此,咱們沒有當即計劃提供降級的支持。可喜的是,Node 11 和更新版本的 Chrome 已經支持這個特性,因此當將編譯目標設定爲 esnext 時你將可以在這些平臺使用 BigInt。
Certain targets may includea polyfill or BigInt-like runtime object. For those purposes you may want toadd esnext.bigint to the lib setting in your compiler options.
某些編譯目標可能包含有兼容包(polyfill)或者相似 BigInt 的運行時對象。出於此目的你可能想要添加 esnext.bigint 到你的編譯器選項的 lib設置中。
Object.defineProperty declarations in JavaScript
JavaScript 中的 Object.defineProperty 聲明
When writing in JavaScriptfiles (using allowJs), TypeScript now recognizes declarations that use Object.defineProperty. This means you’ll get better completions, and stronger type-checking when enabling type-checking in JavaScript files (by turning on the checkJs option or adding a //@ts-check comment to the top of your file).
當編寫 JavaScript 時(使用 allowJs 標誌),TypeScript 如今能識別使用 Object.defineProperty 的聲明瞭。這意味着你將獲得更好的代碼完成,以及當啓用在JavaScript 中進行類型檢查(經過打開 checkJs 選項或者在文件的頂部添加 //@ts-check 註釋來開啓)時更強的類型檢查。
// @ts-check
let obj = {};
Object.defineProperty(obj,"x", { value:"hello", writable:false });
obj.x.toLowercase();
// ~~~
// error:
// Property 'toLowercase' does not exist on type 'string'.
// Did you mean 'toLowerCase'?
obj.x = "world";
// ~
// error:
// Cannot assign to 'x' because it is a read-only property.
Error message improvements
錯誤消息改進
We’re continuing to push improvements in the error experience inTypeScript. Here’s a few things in TypeScript 3.2 that we believe will make the language easier to use.
咱們持續地推動 TypeScript 中的錯誤體驗方面的改進。下面的這些是在 TypeScript 3.2 中咱們相信將會使這個語言更易於使用。
• Better missing property errors (and cleaner missing attributes in JSX)
更好的屬性缺失錯誤提示(以及 JSX 中的更簡潔的特性缺失提示)
• Better error spans in arrays and arrow functions
數組和箭頭函數中更好的錯誤提示(錯誤位置標示)
• Error on most-overlapping types in unions (a.k.a. 「pick most overlappy type」)
聯合類型中覆蓋最廣的類型的錯誤(又名「選取最廣覆蓋類型」)
TypeScript 3.2 以前的報錯信息
TypeScript 3.2 的報錯信息
• Related spans when a typed this is shadowed
當一個具備類型的 this 被隱蔽時的相對跨度提示
TypeScript 3.2 以前的報錯信息
TypeScript 3.2 的報錯信息
• 「Did you forget a semicolon?」 on parenthesized expressions on the next line
「你忘記了分號嗎?」在下一行中的括號表達式上的提示
• More specific messages when assigning to const / readonly bindings
當賦值給 const / readonly 時更具體的信息
TypeScript 3.2 以前的報錯信息
TypeScript 3.2 的報錯信息
• More accurate message when extending complex types
擴展複雜類型時更精準的信息
TypeScript 3.2 以前的報錯信息
TypeScript 3.2 的報錯信息
• Use relative module names in error messages
在錯誤信息中使用相對模塊名稱
TypeScript 3.2 以前的報錯信息
TypeScript 3.2 的報錯信息
Thanks to Kingwl, a-tarasyuk, and prateekgoel who helped out on some of these improvements.
感謝 Kingwl、a-tarasyuk 和 prateekgoel 對這些改進所提供的幫助。
Improved narrowing for tagged unions
改進了的標記式聯合類型的收窄
TypeScript 3.2 makes narrowing easier by relaxing rules for what’s considered a discriminant property. Common properties of unions are now considered discriminants as long as they contain some singleton type (e.g. a string literal, null, or undefined), and they contain no generics.
TypeScript 3.2 經過放寬斷定什麼是判別屬性的規則使類型收窄變得更容易。聯合類型的常規屬性如今被認爲是判別屬性——只要它們包含某些孤立類型(如,字符串字面量,null 或 undefined)且不包含泛型。
As a result, TypeScript 3.2 considers the error property in the following example to be a discriminant, whereas before it wouldn’t since Error isn’t a singleton type. Thanks to this, narrowing works correctly in the body of the unwrap function.
結果,TypeScript 3.2 認爲如下例子中的 error 屬性是一個判別屬性,而在此前的版本中則不是,由於 Error不是一個孤立類型。因爲這點,unwrap 函數體中的收窄可以正確地工做。
type Either<T>=
| { error:Error; data:null}
| { error:null; data:T};
function unwrap<T>(result:Either<T>) {
if(result.error) {
// Here 'error' is non-null throw result.error;
}
// Now 'data' is non-null
return result.data;
}
Editing improvements
編輯改進
The TypeScript project doesn’t simply consist of a compiler/type-checker. The core components of the compiler also provide a cross-platform open-source language service that can power 「smarter」 editor features like go-to-definition, find-all-references, and a number of quick fixes and refactorings. TypeScript 3.2 brings some small quality of life improvements.
TypeScript 項目不是簡單的包含一個編譯器/類型檢查器而已。編譯器的核心組件還提供了一個跨平臺開源的語言服務,它能帶來更「聰明」的編輯器特性,如轉到定義,查找全部引用,以及許多快速修復和重構。TypeScript 3.2 爲生活質量帶來了一些小提高。
Quick fixes
快速修復
Implicit any suggestions and 「inferfrom usage」 fixes
修復隱式 any 建議和「從使用推導」
We strongly suggest users take advantage of stricter checking when possible. noImplicitAny is one of these stricter checking modes, and it helps ensure that your code is as fully typed as possible which also leads to a better editing experience.
咱們強烈建議用戶在可能的時候利用更嚴格的檢查。noImplicitAny 是這些更嚴格的檢查模式之一,且它可以幫助保證你的代碼儘量徹底地類型化同時也可以帶來更好的編輯體驗。
Unfortunately it’s not all roses for existing codebases. noImplicitAny is a big switch across codebases which can lead to a lot of error messages and red squiggles in your editor as you type code. The experience can be jarring to turn on just to find out which variables need types.
不幸的是對於現有的代碼庫來講,這並不都是好的。noImplicitAny 是一個跨代碼庫的大開關,當你輸入代碼時,它會致使編輯器中出現大量的錯誤消息和紅色波浪線。只是爲了找出哪一個變量須要類型,這種體驗可能會讓人震驚。
In this release, TypeScript produces suggestions for most variables and parameters that would have been reported as having implicit any types. When an editor reports these suggestions, TypeScript also provides a quick fix to automatically infer the types for you.
在這個版本中,TypeScript 爲大多數變量和參數產生建議,這些變量和參數將被報告爲具備隱式any 類型。當編輯器報告這些建議時,TypeScript也提供一個快速修復來爲你自動推導這些類型。
This can make migrating an existing codebase to TypeScript even easier, and we expect it will make migrating to noImplicitAny a breeze.
這使得遷移現有代碼庫到 TypeScript 更容易,同時咱們但願它可以使得遷移到noImplicitAny 變得垂手可得。
Going a step further,TypeScript users who are type-checking their .js files using checkJs or the // @ts-check comments can now also getthe same functionality with JSDoc types!
更進一步,經過使用 JSDoc類型,那些使用checkJs 或者 // @ts-check 註釋來對他們的 .js文件進行類型檢查的 TypeScript 用戶如今一樣能夠獲得相同的功能。
Other fixes
其它修復
TypeScript 3.2 also brings two smaller quick fixes for small mistakes.
TypeScript 3.2 一樣爲小錯誤帶來了兩個更小的快速修復。
• Add a missing new when accidentally calling a constructor.
當意外地調用了構造函數時添加一個缺失的new。
• Add an intermediate assertion to unknown when types are sufficiently unrelated.
當類型徹底無關時添加一箇中間斷言到unknown。
Thanks to GitHub users iliashkolyar and ryanclarke respectively for these changes!
感謝 GitHub 用戶 iliashkolyar 和 ryanclarke 分別爲這些改變作的貢獻。
Improved formatting
改進的格式化
Thanks to saschanaz,TypeScript is now smarter about formatting several different constructs. Listing all of them might be a bit cumbersome, but you can take a look at the pull request here.
感謝 saschanaz,TypeScript 如今對於格式化多個不一樣的結構更加的聰明瞭。列出全部的這些可能會有點繁重,可是你能夠在這裏查看拉取請求。
Breaking changes and deprecations
破壞性變動和棄用項
lib.d.ts changes
lib.d.ts 的變動
TypeScript has recently moved more to generating DOM declarations in lib.d.ts by leveraging IDL files provided by standards groups. Upgraders should note take note of any issues they encounter related to the DOM and report them.
TypeScript 最近經過利用標準組提供的 IDL 文件,已經在 lib.d.ts中生成更多的 DOM 聲明。升級者應注意他們遇到的與DOM相關的任何問題並報告它們。
More specific types
更具體的類型
Certain parameters no longer accept null, or now accept more specific types as per the corresponding specifications that describe the DOM.
某些參數再也不接受 null,或者按照那些描述 DOM的對應的規範如今接受更具體的類型。
More platform-specific deprecations
更多特定於平臺的棄用項
Certain properties that are WebKit-specific have been deprecated. They are likely to be removed in a new version.
某些 WebKit 特定的屬性已經被棄用。在新版本中它們極可能被移除。
wheelDelta and friends have been removed.
wheelDelta 及其關聯項已經被移除
wheelDeltaX, wheelDelta, and wheelDeltaZ have all been removed as they are deprecated properties on WheelEvents.
wheelDeltaX、wheelDelta 和 wheelDeltaZ 都已被移除,由於它們是WheelEvent 上的棄用屬性。
As a solution, you can use deltaX, deltaY, and deltaZ instead. If older runtimes are a concern, you can include a file called legacy.d.ts in your project and write the following in it:
你可使用 deltaX、deltaY 和 deltaZ 來替代做爲一個解決方案。若是要兼顧更舊版本的運行時,你能夠在項目中包含一個叫 legacy.d.ts 的文件並在其中編寫以下內容:
// legacy.d.ts
interface WheelEvent {
readonly wheelDelta:number; readonly wheelDeltaX:number; readonly wheelDeltaZ:number;
}
JSX resolution changes
JSX 解決方案的變動
Our logic for resolving JSX invocations has been unified with our logic for resolving function calls. While this has simplified the compiler codebase and improved some use-cases, there may be some differences which we may need to reconcile. These changes are likely unintentional so they are not breaking changes per se, but upgraders should note take note of any issues they encounter and report them.
咱們用於解析 JSX 調用的邏輯已經統一爲使用用於解析函數調用的邏輯。雖然這簡化了編譯器代碼庫並改進了一些用例,可是咱們可能須要調解某些差別。這些變動多是無心的,故它們自己沒有破壞變動,可是升級者應注意他們遇到的任何問題並報告它們。
A note for NuGet and Visual Studio 2015
NuGet 和 Visual Studio 2015 要注意的一點
We have some changes comingin TypeScript 3.2 for NuGet and VS2015 users.
在 TypeScript 3.2 中咱們爲 NuGet 和 VS 2015的用戶帶來了一些變化。
First, TypeScript 3.2 and future releases will only ship an MSBuild package, and not a standalone compiler package. Second, while our NuGet packages previously shipped with the Chakra JavaScript engine to run the compiler, the MSBuild package now depends on an invokable version of Node.js to be present. While machines with newer versions of Visual Studio 2017 (versions 15.8 and above) will not be impacted, some testing / CI machines, users with Visual Studio 2015, and users of Visual Studio 2017 15.7 and below may need to install Node.js directly from the site, through Visual Studio 2017 Build Tools (read more here), or via a redistribution of Node.js over NuGet. Otherwise, upgrading toTypeScript 3.2 might result in a build error like the following:
首先,TypeScript 3.2 及未來的版本將只發佈一個MSBuild 包而不是一個獨立的編譯器包。其次,雖然之前咱們的 NuGet 包伴隨着 Chakra JavaScript 引擎一塊兒發佈以運行編譯器,可是MSBuild 包如今將以依賴於一個可調用的Node.js 版本的形式出現。雖然那些更新的版本的Visual Studio 2017(版本 15.8 及以上)的機器不會受影響,可是某些測試 / CI 機器、Visual Studio 2015 的用戶以及 Visual Studio 2017 15.7 版本和更低版本的用戶可能須要直接從站點安裝 Node.js,經過 Visual Studio 2017 構建工具(瞭解更多),或者經過在 NuGet 上分發的Node.js 來安裝。不然,更新到TypeScript 3.2可能會形成以下的構建錯誤:
The build task could not find node.exe which is required to run the TypeScript compiler. Please install Node and ensure that the system path contains its location.
構建任務沒法找到 node.exe,它是運行 TypeScript編譯器所必需的。請安裝 Node 並確保系統環境變量中的「path」包含了它的位置。
Lastly, TypeScript 3.2 will be the last TypeScript release with editor support for Visual Studio 2015 users. To stay current with TypeScript, we recommend upgrading to Visual Studio 2017 for the latest editing experience.
最後,TypeScript 3.2 將會是支持 Visual Studio 2015 用戶的最後一個 TypeScript 版本。爲了保持與 TypeScript 版本一致,咱們推薦升級到 Visual Studio 2017 以得到最新的編輯體驗。
What’s next
下一步是什麼
Our next release of TypeScript is slated for the end of January. Some things we’ve got planned on the horizon are partial type argument inference and a quick fix to scaffold out declaration files that don’t exist on DefinitelyTyped. While this list is influx, you can keep track of our plans on the TypeScript Roadmap.
咱們的下一個 TypeScript 版本預計是在(2019 年)一月末。咱們已經有了眉目的一些事情是:部分類型參數推斷和快速修復以生成那些DefinitelyDyped 中不存在的聲明文件。雖然這個列表在不斷變化,但你能夠在TypeScript 路線圖上跟蹤咱們的計劃。
We hope that TypeScript 3.2 makes your day-to-day coding more enjoyable, whether it comes to expressivity, productivity, or ease-of-use. If you’re enjoying it, drop us a line on Twitterat @typescriptlang; and if you’ve got ideas on what we should improve, file an issue on GitHub.
不管是表現力,生產力仍是易用性,咱們但願TypeScript 3.2 能讓你的平常編程更開心。若是你喜歡它,請在 Twitter 上給 @typescriptlang 留言;若是你對咱們應該做何改進有想法,請在 GitHub 上建立一個 issue 告知咱們。
Happy hacking!
嗨起來吧!
– Daniel Rosenwasser and theTypeScript team
——Daniel Rosenwasser 和 TypeScript 團隊
本文爲公衆號「TypeScript社區(QQ 羣號 390037547)」原創翻譯,轉載請註明出處!不然追究法律責任!