|
| 1 | +## Stricter Generators |
| 2 | + |
| 3 | +TypeScript 3.6 introduces stricter checking for iterators and generator functions. |
| 4 | +In earlier versions, users of generators had no way to differentiate whether a value was yielded or returned from a generator. |
| 5 | + |
| 6 | +```ts |
| 7 | +function* foo() { |
| 8 | + if (Math.random() < 0.5) yield 100; |
| 9 | + return "Finished!" |
| 10 | +} |
| 11 | + |
| 12 | +let iter = foo(); |
| 13 | +let curr = iter.next(); |
| 14 | +if (curr.done) { |
| 15 | + // TypeScript 3.5 and prior thought this was a 'string | number'. |
| 16 | + // It should know it's 'string' since 'done' was 'true'! |
| 17 | + curr.value |
| 18 | +} |
| 19 | +``` |
| 20 | + |
| 21 | +Additionally, generators just assumed the type of `yield` was always `any`. |
| 22 | + |
| 23 | +```ts |
| 24 | +function* bar() { |
| 25 | + let x: { hello(): void } = yield; |
| 26 | + x.hello(); |
| 27 | +} |
| 28 | + |
| 29 | +let iter = bar(); |
| 30 | +iter.next(); |
| 31 | +iter.next(123); // oops! runtime error! |
| 32 | +``` |
| 33 | + |
| 34 | +In TypeScript 3.6, the checker now knows that the correct type for `curr.value` should be `string` in our first example, and will correctly error on our call to `next()` in our last example. |
| 35 | +This is thanks to some changes in the `Iterator` and `IteratorResult` type declarations to include a few new type parameters, and to a new type that TypeScript uses to represent generators called the `Generator` type. |
| 36 | + |
| 37 | +The `Iterator` type now allows users to specify the yielded type, the returned type, and the type that `next` can accept. |
| 38 | + |
| 39 | +```ts |
| 40 | +interface Iterator<T, TReturn = any, TNext = undefined> { |
| 41 | + // Takes either 0 or 1 arguments - doesn't accept 'undefined' |
| 42 | + next(...args: [] | [TNext]): IteratorResult<T, TReturn>; |
| 43 | + return?(value?: TReturn): IteratorResult<T, TReturn>; |
| 44 | + throw?(e?: any): IteratorResult<T, TReturn>; |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +Building on that work, the new `Generator` type is an `Iterator` that always has both the `return` and `throw` methods present, and is also iterable. |
| 49 | + |
| 50 | +```ts |
| 51 | +interface Generator<T = unknown, TReturn = any, TNext = unknown> |
| 52 | + extends Iterator<T, TReturn, TNext> { |
| 53 | + next(...args: [] | [TNext]): IteratorResult<T, TReturn>; |
| 54 | + return(value: TReturn): IteratorResult<T, TReturn>; |
| 55 | + throw(e: any): IteratorResult<T, TReturn>; |
| 56 | + [Symbol.iterator](): Generator<T, TReturn, TNext>; |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +To allow differentiation between returned values and yielded values, TypeScript 3.6 converts the `IteratorResult` type to a discriminated union type: |
| 61 | + |
| 62 | +```ts |
| 63 | +type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>; |
| 64 | + |
| 65 | +interface IteratorYieldResult<TYield> { |
| 66 | + done?: false; |
| 67 | + value: TYield; |
| 68 | +} |
| 69 | + |
| 70 | +interface IteratorReturnResult<TReturn> { |
| 71 | + done: true; |
| 72 | + value: TReturn; |
| 73 | +} |
| 74 | +``` |
| 75 | + |
| 76 | +In short, what this means is that you'll be able to appropriately narrow down values from iterators when dealing with them directly. |
| 77 | + |
| 78 | +To correctly represent the types that can be passed in to a generator from calls to `next()`, TypeScript 3.6 also infers certain uses of `yield` within the body of a generator function. |
| 79 | + |
| 80 | +```ts |
| 81 | +function* foo() { |
| 82 | + let x: string = yield; |
| 83 | + console.log(x.toUpperCase()); |
| 84 | +} |
| 85 | + |
| 86 | +let x = foo(); |
| 87 | +x.next(); // first call to 'next' is always ignored |
| 88 | +x.next(42); // error! 'number' is not assignable to 'string' |
| 89 | +``` |
| 90 | + |
| 91 | +If you'd prefer to be explicit, you can also enforce the type of values that can be returned, yielded, and evaluated from `yield` expressions using an explicit return type. |
| 92 | +Below, `next()` can only be called with `boolean`s, and depending on the value of `done`, `value` is either a `string` or a `number`. |
| 93 | + |
| 94 | +```ts |
| 95 | +/** |
| 96 | + * - yields numbers |
| 97 | + * - returns strings |
| 98 | + * - can be passed in booleans |
| 99 | + */ |
| 100 | +function* counter(): Generator<number, string, boolean> { |
| 101 | + let i = 0; |
| 102 | + while (true) { |
| 103 | + if (yield i++) { |
| 104 | + break; |
| 105 | + } |
| 106 | + } |
| 107 | + return "done!"; |
| 108 | +} |
| 109 | + |
| 110 | +var iter = counter(); |
| 111 | +var curr = iter.next() |
| 112 | +while (!curr.done) { |
| 113 | + console.log(curr.value); |
| 114 | + curr = iter.next(curr.value === 5) |
| 115 | +} |
| 116 | +console.log(curr.value.toUpperCase()); |
| 117 | + |
| 118 | +// prints: |
| 119 | +// |
| 120 | +// 0 |
| 121 | +// 1 |
| 122 | +// 2 |
| 123 | +// 3 |
| 124 | +// 4 |
| 125 | +// 5 |
| 126 | +// DONE! |
| 127 | +``` |
| 128 | + |
| 129 | +For more details on the change, [see the pull request here](https://github.com/Microsoft/TypeScript/issues/2983). |
| 130 | + |
| 131 | +## More Accurate Array Spread |
| 132 | + |
| 133 | +In pre-ES2015 targets, the most faithful emit for constructs like `for`/`of` loops and array spreads can be a bit heavy. |
| 134 | +For this reason, TypeScript uses a simpler emit by default that only supports array types, and supports iterating on other types using the `--downlevelIteration` flag. |
| 135 | +The looser default without `--downlevelIteration` works fairly well; however, there were some common cases where the transformation of array spreads had observable differences. |
| 136 | +For example, the following array containing a spread |
| 137 | + |
| 138 | +```ts |
| 139 | +[...Array(5)] |
| 140 | +``` |
| 141 | + |
| 142 | +can be rewritten as the following array literal |
| 143 | + |
| 144 | +```js |
| 145 | +[undefined, undefined, undefined, undefined, undefined] |
| 146 | +``` |
| 147 | + |
| 148 | +However, TypeScript would instead transform the original code into this code: |
| 149 | + |
| 150 | +```ts |
| 151 | +Array(5).slice(); |
| 152 | +``` |
| 153 | + |
| 154 | +which is slightly different. |
| 155 | +`Array(5)` produces an array with a length of 5, but with no defined property slots. |
| 156 | + |
| 157 | +TypeScript 3.6 introduces a new `__spreadArrays` helper to accurately model what happens in ECMAScript 2015 in older targets outside of `--downlevelIteration`. |
| 158 | +`__spreadArrays` is also available in [tslib](https://github.com/Microsoft/tslib/). |
| 159 | + |
| 160 | +For more information, [see the relevant pull request](https://github.com/microsoft/TypeScript/pull/31166). |
| 161 | + |
| 162 | +## Improved UX Around Promises |
| 163 | + |
| 164 | +TypeScript 3.6 introduces some improvements for when `Promise`s are mis-handled. |
| 165 | + |
| 166 | +For example, it's often very common to forget to `.then()` or `await` the contents of a `Promise` before passing it to another function. |
| 167 | +TypeScript's error messages are now specialized, and inform the user that perhaps they should consider using the `await` keyword. |
| 168 | + |
| 169 | +```ts |
| 170 | +interface User { |
| 171 | + name: string; |
| 172 | + age: number; |
| 173 | + location: string; |
| 174 | +} |
| 175 | + |
| 176 | +declare function getUserData(): Promise<User>; |
| 177 | +declare function displayUser(user: User): void; |
| 178 | + |
| 179 | +async function f() { |
| 180 | + displayUser(getUserData()); |
| 181 | +// ~~~~~~~~~~~~~ |
| 182 | +// Argument of type 'Promise<User>' is not assignable to parameter of type 'User'. |
| 183 | +// ... |
| 184 | +// Did you forget to use 'await'? |
| 185 | +} |
| 186 | +``` |
| 187 | + |
| 188 | +It's also common to try to access a method before `await`-ing or `.then()`-ing a `Promise`. |
| 189 | +This is another example, among many others, where we're able to do better. |
| 190 | + |
| 191 | +```ts |
| 192 | +async function getCuteAnimals() { |
| 193 | + fetch("https://reddit.com/r/aww.json") |
| 194 | + .json() |
| 195 | + // ~~~~ |
| 196 | + // Property 'json' does not exist on type 'Promise<Response>'. |
| 197 | + // |
| 198 | + // Did you forget to use 'await'? |
| 199 | +} |
| 200 | +``` |
| 201 | + |
| 202 | +For more details, [see the originating issue](https://github.com/microsoft/TypeScript/issues/30646), as well as the pull requests that link back to it. |
| 203 | + |
| 204 | +## Better Unicode Support for Identifiers |
| 205 | + |
| 206 | +TypeScript 3.6 contains better support for Unicode characters in identifiers when emitting to ES2015 and later targets. |
| 207 | + |
| 208 | +```ts |
| 209 | +const 𝓱𝓮𝓵𝓵𝓸 = "world"; // previously disallowed, now allowed in '--target es2015' |
| 210 | +``` |
| 211 | + |
| 212 | +## `import.meta` Support in SystemJS |
| 213 | + |
| 214 | +TypeScript 3.6 supports transforming `import.meta` to `context.meta` when your `module` target is set to `system`. |
| 215 | + |
| 216 | +```ts |
| 217 | +// This module: |
| 218 | + |
| 219 | +console.log(import.meta.url) |
| 220 | + |
| 221 | +// gets turned into the following: |
| 222 | + |
| 223 | +System.register([], function (exports, context) { |
| 224 | + return { |
| 225 | + setters: [], |
| 226 | + execute: function () { |
| 227 | + console.log(context.meta.url); |
| 228 | + } |
| 229 | + }; |
| 230 | +}); |
| 231 | +``` |
| 232 | + |
| 233 | +## `get` and `set` Accessors Are Allowed in Ambient Contexts |
| 234 | + |
| 235 | +In previous versions of TypeScript, the language didn't allow `get` and `set` accessors in ambient contexts (like in `declare`-d classes, or in `.d.ts` files in general). |
| 236 | +The rationale was that accessors weren't distinct from properties as far as writing and reading to these properties; |
| 237 | +however, [because ECMAScript's class fields proposal may have differing behavior from in existing versions of TypeScript](https://github.com/tc39/proposal-class-fields/issues/248), we realized we needed a way to communicate this different behavior to provide appropriate errors in subclasses. |
| 238 | + |
| 239 | +As a result, users can write getters and setters in ambient contexts in TypeScript 3.6. |
| 240 | + |
| 241 | +```ts |
| 242 | +declare class Foo { |
| 243 | + // Allowed in 3.6+. |
| 244 | + get x(): number; |
| 245 | + set x(val: number): void; |
| 246 | +} |
| 247 | +``` |
| 248 | + |
| 249 | +In TypeScript 3.7, the compiler itself will take advantage of this feature so that generated `.d.ts` files will also emit `get`/`set` accessors. |
| 250 | + |
| 251 | +## Ambient Classes and Functions Can Merge |
| 252 | + |
| 253 | +In previous versions of TypeScript, it was an error to merge classes and functions under any circumstances. |
| 254 | +Now, ambient classes and functions (classes/functions with the `declare` modifier, or in `.d.ts` files) can merge. |
| 255 | +This means that now you can write the following: |
| 256 | + |
| 257 | +```ts |
| 258 | +export declare function Point2D(x: number, y: number): Point2D; |
| 259 | +export declare class Point2D { |
| 260 | + x: number; |
| 261 | + y: number; |
| 262 | + constructor(x: number, y: number); |
| 263 | +} |
| 264 | +``` |
| 265 | + |
| 266 | +instead of needing to use |
| 267 | + |
| 268 | +```ts |
| 269 | +export interface Point2D { |
| 270 | + x: number; |
| 271 | + y: number; |
| 272 | +} |
| 273 | +export declare var Point2D: { |
| 274 | + (x: number, y: number): Point2D; |
| 275 | + new (x: number, y: number): Point2D; |
| 276 | +} |
| 277 | +``` |
| 278 | +
|
| 279 | +One advantage of this is that the callable constructor pattern can be easily expressed while also allowing namespaces to merge with these declarations (since `var` declarations can't merge with `namespace`s). |
| 280 | + |
| 281 | +In TypeScript 3.7, the compiler will take advantage of this feature so that `.d.ts` files generated from `.js` files can appropriately capture both the callability and constructability of a class-like function. |
| 282 | + |
| 283 | +For more details, [see the original PR on GitHub](https://github.com/microsoft/TypeScript/pull/32584). |
| 284 | + |
| 285 | +## APIs to Support `--build` and `--incremental` |
| 286 | + |
| 287 | +TypeScript 3.0 introduced support for referencing other and building them incrementally using the `--build` flag. |
| 288 | +Additionally, TypeScript 3.4 introduced the `--incremental` flag for saving information about previous compilations to only rebuild certain files. |
| 289 | +These flags were incredibly useful for structuring projects more flexibly and speeding builds up. |
| 290 | +Unfortunately, using these flags didn't work with 3rd party build tools like Gulp and Webpack. |
| 291 | +TypeScript 3.6 now exposes two sets of APIs to operate on project references and incremental program building. |
| 292 | + |
| 293 | +For creating `--incremental` builds, users can leverage the `createIncrementalProgram` and `createIncrementalCompilerHost` APIs. |
| 294 | +Users can also re-hydrate old program instances from `.tsbuildinfo` files generated by this API using the newly exposed `readBuilderProgram` function, which is only meant to be used as for creating new programs (i.e. you can't modify the returned instance - it's only meant to be used for the `oldProgram` parameter in other `create*Program` functions). |
| 295 | + |
| 296 | +For leveraging project references, a new `createSolutionBuilder` function has been exposed, which returns an instance of the new type `SolutionBuilder`. |
| 297 | + |
| 298 | +For more details on these APIs, you can [see the original pull request](https://github.com/microsoft/TypeScript/pull/31432). |
| 299 | + |
| 300 | +## Semicolon-Aware Code Edits |
| 301 | + |
| 302 | +Editors like Visual Studio and Visual Studio Code can automatically apply quick fixes, refactorings, and other transformations like automatically importing values from other modules. |
| 303 | +These transformations are powered by TypeScript, and older versions of TypeScript unconditionally added semicolons to the end of every statement; unfortunately, this disagreed with many users' style guidelines, and many users were displeased with the editor inserting semicolons. |
| 304 | + |
| 305 | +TypeScript is now smart enough to detect whether your file uses semicolons when applying these sorts of edits. |
| 306 | +If your file generally lacks semicolons, TypeScript won't add one. |
| 307 | + |
| 308 | +For more details, [see the corresponding pull request](https://github.com/microsoft/TypeScript/pull/31801). |
| 309 | + |
| 310 | +## Smarter Auto-Import Syntax |
| 311 | + |
| 312 | +JavaScript has a lot of different module syntaxes or conventions: the one in the ECMAScript standard, the one Node already supports (CommonJS), AMD, System.js, and more! |
| 313 | +For the most part, TypeScript would default to auto-importing using ECMAScript module syntax, which was often inappropriate in certain TypeScript projects with different compiler settings, or in Node projects with plain JavaScript and `require` calls. |
| 314 | + |
| 315 | +TypeScript 3.6 is now a bit smarter about looking at your existing imports before deciding on how to auto-import other modules. |
| 316 | +You can [see more details in the original pull request here](https://github.com/microsoft/TypeScript/pull/32684). |
| 317 | + |
| 318 | +## `await` Completions on Promises |
| 319 | + |
| 320 | +In TypeScript 3.6, completions on an |
| 321 | + |
| 322 | +## New TypeScript Playground |
| 323 | + |
| 324 | +The TypeScript playground has received a much-needed refresh with handy new functionality! |
| 325 | +The new playground is largely a fork of [Artem Tyurin](https://github.com/agentcooper)'s [TypeScript playground](https://github.com/agentcooper/typescript-play) which community members have been using more and more. |
| 326 | +We owe Artem a big thanks for helping out here! |
| 327 | + |
| 328 | +The new playground now supports many new options including: |
| 329 | + |
| 330 | +* The `target` option (allowing users to switch out of `es5` to `es3`, `es2015`, `esnext`, etc.) |
| 331 | +* All the strictness flags (including just `strict`) |
| 332 | +* Support for plain JavaScript files (using `allowJS` and optionally `checkJs`) |
| 333 | + |
| 334 | +These options also persist when sharing links to playground samples, allowing users to more reliably share examples without having to tell the recipient "oh, don't forget to turn on the `noImplicitAny` option!". |
| 335 | + |
| 336 | +In the near future, we're going to be refreshing the playground samples, adding JSX support, and polishing automatic type acquisition, meaning that you'll be able to see the same experience on the playground as you'd get in your personal editor. |
| 337 | + |
| 338 | +As we improve the playground and the website, [we welcome feedback and pull requests on GitHub](https://github.com/microsoft/TypeScript-Website/)! |
0 commit comments