{"id":4017,"date":"2023-08-24T08:53:20","date_gmt":"2023-08-24T16:53:20","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/typescript\/?p=4017"},"modified":"2023-08-24T13:23:24","modified_gmt":"2023-08-24T21:23:24","slug":"announcing-typescript-5-2","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/typescript\/announcing-typescript-5-2\/","title":{"rendered":"Announcing TypeScript 5.2"},"content":{"rendered":"<p>Today we&#8217;re excited to announce the release of TypeScript 5.2!<\/p>\n<p>If you&#8217;re not familiar with TypeScript, it&#8217;s a language that builds on top of JavaScript by making it possible to declare and describe types.\nWriting types in our code allows us to explain intent and have other tools check our code to catch mistakes like typos, issues with <code>null<\/code> and <code>undefined<\/code>, and more.\nTypes also power TypeScript&#8217;s editor tooling like the auto-completion, code navigation, and refactorings that you might see in Visual Studio and VS Code.\nIn fact, if you&#8217;ve been writing JavaScript in either of those editors, you&#8217;ve been using TypeScript all this time!<\/p>\n<p>To get started using TypeScript through npm with the following command:<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>npm install -D typescript\r\n<\/code><\/pre>\n<p>or <a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.TypeScript.MSBuild\">through NuGet<\/a>.<\/p>\n<p>Here&#8217;s a quick list of what&#8217;s new in TypeScript 5.2!<\/p>\n<ul>\n<li><a href=\"#using-declarations-and-explicit-resource-management\"><code>using<\/code> Declarations and Explicit Resource Management<\/a><\/li>\n<li><a href=\"#decorator-metadata\">Decorator Metadata<\/a><\/li>\n<li><a href=\"#named-and-anonymous-tuple-elements\">Named and Anonymous Tuple Elements<\/a><\/li>\n<li><a href=\"#easier-method-usage-for-unions-of-arrays\">Easier Method Usage for Unions of Arrays<\/a><\/li>\n<li><a href=\"#copying-array-methods\">Copying Array Methods<\/a><\/li>\n<li><a href=\"#symbols-as-weakmap-and-weakset-keys\"><code>symbol<\/code>s as <code>WeakMap<\/code> and <code>WeakSet<\/code> Keys<\/a><\/li>\n<li><a href=\"#type-only-import-paths-with-typescript-implementation-file-extensions\">Type-Only Import Paths with TypeScript Implementation File Extensions<\/a><\/li>\n<li><a href=\"#comma-completions-for-object-members\">Comma Completions for Object Members<\/a><\/li>\n<li><a href=\"#inline-variable-refactoring\">Inline Variable Refactoring<\/a><\/li>\n<li><a href=\"#clickable-inlay-parameter-hints\">Clickable Inlay Parameter Hints<\/a><\/li>\n<li><a href=\"#optimized-checks-for-ongoing-type-compatibility\">Optimized Checks for Ongoing Type Compatibility<\/a><\/li>\n<li><a href=\"#breaking-changes-and-correctness-fixes\">Breaking Changes and Correctness Fixes<\/a><\/li>\n<\/ul>\n<h2>What&#8217;s New Since the Beta and RC?<\/h2>\n<p><a href=\"https:\/\/devblogs.microsoft.com\/typescript\/announcing-typescript-5-2-beta\/\">Since the Beta<\/a>, we&#8217;ve added <a href=\"#optimized-checks-for-ongoing-type-compatibility\">a type-checking optimization<\/a> and <a href=\"#type-only-import-paths-with-typescript-implementation-file-extensions\">made it possible to reference the paths of TypeScript implementation files in type-only imports<\/a>.<\/p>\n<p>Since the RC, we&#8217;ve also documented the addition of <a href=\"#copying-array-methods\">Copying Array Methods<\/a>, <a href=\"#symbols-as-weakmap-and-weakset-keys\"><code>symbol<\/code>s as <code>WeakMap<\/code> and <code>WeakSet<\/code> Keys<\/a> and <a href=\"#clickable-inlay-parameter-hints\">Clickable Inlay Parameter Hints<\/a>.\nThis release also documents <a href=\"#modules-always-emits-as-namespace\">a small breaking change around always emitting the <code>namespace<\/code> keyword in declaration files<\/a>.<\/p>\n<h2><code>using<\/code> Declarations and Explicit Resource Management<\/h2>\n<p>TypeScript 5.2 adds support for the upcoming <a href=\"https:\/\/github.com\/tc39\/proposal-explicit-resource-management\">Explicit Resource Management<\/a> feature in ECMAScript.\nLet&#8217;s explore some of the motivations and understand what the feature brings us.<\/p>\n<p>It&#8217;s common to need to do some sort of &quot;clean-up&quot; after creating an object.\nFor example, you might need to close network connections, delete temporary files, or just free up some memory.<\/p>\n<p>Let&#8217;s imagine a function that creates a temporary file, reads and writes to it for various operations, and then closes and deletes it.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>import * as fs from \"fs\";\r\n\r\nexport function doSomeWork() {\r\n    const path = \".some_temp_file\";\r\n    const file = fs.openSync(path, \"w+\");\r\n\r\n    \/\/ use file...\r\n\r\n    \/\/ Close the file and delete it.\r\n    fs.closeSync(file);\r\n    fs.unlinkSync(path);\r\n}\r\n<\/code><\/pre>\n<p>This is fine, but what happens if we need to perform an early exit?<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>export function doSomeWork() {\r\n    const path = \".some_temp_file\";\r\n    const file = fs.openSync(path, \"w+\");\r\n\r\n    \/\/ use file...\r\n    if (someCondition()) {\r\n        \/\/ do some more work...\r\n\r\n        \/\/ Close the file and delete it.\r\n        fs.closeSync(file);\r\n        fs.unlinkSync(path);\r\n        return;\r\n    }\r\n\r\n    \/\/ Close the file and delete it.\r\n    fs.closeSync(file);\r\n    fs.unlinkSync(path);\r\n}\r\n<\/code><\/pre>\n<p>We&#8217;re starting to see some duplication of clean-up which can be easy to forget.\nWe&#8217;re also not guaranteed to close and delete the file if an error gets thrown.\nThis could be solved by wrapping this all in a <code>try<\/code>\/<code>finally<\/code> block.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>export function doSomeWork() {\r\n    const path = \".some_temp_file\";\r\n    const file = fs.openSync(path, \"w+\");\r\n\r\n    try {\r\n        \/\/ use file...\r\n\r\n        if (someCondition()) {\r\n            \/\/ do some more work...\r\n            return;\r\n        }\r\n    }\r\n    finally {\r\n        \/\/ Close the file and delete it.\r\n        fs.closeSync(file);\r\n        fs.unlinkSync(path);\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>While this is more robust, it&#8217;s added quite a bit of &quot;noise&quot; to our code.\nThere are also other foot-guns we can run into if we start adding more clean-up logic to our <code>finally<\/code> block \u2014 for example, exceptions preventing other resources from being disposed.\nThis is what the <a href=\"https:\/\/github.com\/tc39\/proposal-explicit-resource-management\">explicit resource management<\/a> proposal aims to solve.\nThe key idea of the proposal is to support resource disposal \u2014 this clean-up work we&#8217;re trying to deal with \u2014 as a first class idea in JavaScript.<\/p>\n<p>This starts by adding a new built-in <code>symbol<\/code> called <code>Symbol.dispose<\/code>, and we can create objects with methods named by <code>Symbol.dispose<\/code>.\nFor convenience, TypeScript defines a new global type called <code>Disposable<\/code> which describes these.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>class TempFile implements Disposable {\r\n    #path: string;\r\n    #handle: number;\r\n\r\n    constructor(path: string) {\r\n        this.#path = path;\r\n        this.#handle = fs.openSync(path, \"w+\");\r\n    }\r\n\r\n    \/\/ other methods\r\n\r\n    [Symbol.dispose]() {\r\n        \/\/ Close the file and delete it.\r\n        fs.closeSync(this.#handle);\r\n        fs.unlinkSync(this.#path);\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>Later on we can call those methods.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>export function doSomeWork() {\r\n    const file = new TempFile(\".some_temp_file\");\r\n\r\n    try {\r\n        \/\/ ...\r\n    }\r\n    finally {\r\n        file[Symbol.dispose]();\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>Moving the clean-up logic to <code>TempFile<\/code> itself doesn&#8217;t buy us much;\nwe&#8217;ve basically just moved all the clean-up work from the <code>finally<\/code> block into a method, and that&#8217;s always been possible.\nBut having a well-known &quot;name&quot; for this method means that JavaScript can build other features on top of it.<\/p>\n<p>That brings us to the first star of the feature: <code>using<\/code> declarations!\n<code>using<\/code> is a new keyword that lets us declare new fixed bindings, kind of like <code>const<\/code>.\nThe key difference is that variables declared with <code>using<\/code> get their <code>Symbol.dispose<\/code> method called at the end of the scope!<\/p>\n<p>So we could simply have written our code like this:<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>export function doSomeWork() {\r\n    using file = new TempFile(\".some_temp_file\");\r\n\r\n    \/\/ use file...\r\n\r\n    if (someCondition()) {\r\n        \/\/ do some more work...\r\n        return;\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>Check it out \u2014 no <code>try<\/code>\/<code>finally<\/code> blocks!\nAt least, none that we see.\nFunctionally, that&#8217;s exactly what <code>using<\/code> declarations will do for us, but we don&#8217;t have to deal with that.<\/p>\n<p>You might be familiar with <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/csharp\/language-reference\/proposals\/csharp-8.0\/using\"><code>using<\/code> declarations in C#<\/a>, <a href=\"https:\/\/docs.python.org\/3\/reference\/compound_stmts.html#the-with-statement\"><code>with<\/code> statements in Python<\/a>, or <a href=\"https:\/\/docs.oracle.com\/javase\/tutorial\/essential\/exceptions\/tryResourceClose.html\"><code>try<\/code>-with-resource declarations in Java<\/a>.\nThese are all similar to JavaScript&#8217;s new <code>using<\/code> keyword, and provide a similar explicit way to perform a &quot;tear-down&quot; of an object at the end of a scope.<\/p>\n<p><code>using<\/code> declarations do this clean-up at the very end of their containing scope or right before an &quot;early return&quot; like a <code>return<\/code> or a <code>throw<\/code>n error.\nThey also dispose in a first-in-last-out order like a stack.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>function loggy(id: string): Disposable {\r\n    console.log(`Creating ${id}`);\r\n\r\n    return {\r\n        [Symbol.dispose]() {\r\n            console.log(`Disposing ${id}`);\r\n        }\r\n    }\r\n}\r\n\r\nfunction func() {\r\n    using a = loggy(\"a\");\r\n    using b = loggy(\"b\");\r\n    {\r\n        using c = loggy(\"c\");\r\n        using d = loggy(\"d\");\r\n    }\r\n    using e = loggy(\"e\");\r\n    return;\r\n\r\n    \/\/ Unreachable.\r\n    \/\/ Never created, never disposed.\r\n    using f = loggy(\"f\");\r\n}\r\n\r\nfunc();\r\n\/\/ Creating a\r\n\/\/ Creating b\r\n\/\/ Creating c\r\n\/\/ Creating d\r\n\/\/ Disposing d\r\n\/\/ Disposing c\r\n\/\/ Creating e\r\n\/\/ Disposing e\r\n\/\/ Disposing b\r\n\/\/ Disposing a\r\n<\/code><\/pre>\n<p><code>using<\/code> declarations are supposed to be resilient to exceptions;\nif an error is thrown, it&#8217;s rethrown after disposal.\nOn the other hand, the body of your function might execute as expected, but the <code>Symbol.dispose<\/code> might throw.\nIn that case, that exception is rethrown as well.<\/p>\n<p>But what happens if both the logic before and during disposal throws an error?\nFor those cases, <code>SuppressedError<\/code> has been introduced as a new subtype of <code>Error<\/code>.\nIt features a <code>suppressed<\/code> property that holds the last-thrown error, and an <code>error<\/code> property for the most-recently thrown error.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>class ErrorA extends Error {\r\n    name = \"ErrorA\";\r\n}\r\nclass ErrorB extends Error {\r\n    name = \"ErrorB\";\r\n}\r\n\r\nfunction throwy(id: string) {\r\n    return {\r\n        [Symbol.dispose]() {\r\n            throw new ErrorA(`Error from ${id}`);\r\n        }\r\n    };\r\n}\r\n\r\nfunction func() {\r\n    using a = throwy(\"a\");\r\n    throw new ErrorB(\"oops!\")\r\n}\r\n\r\ntry {\r\n    func();\r\n}\r\ncatch (e: any) {\r\n    console.log(e.name); \/\/ SuppressedError\r\n    console.log(e.message); \/\/ An error was suppressed during disposal.\r\n\r\n    console.log(e.error.name); \/\/ ErrorA\r\n    console.log(e.error.message); \/\/ Error from a\r\n\r\n    console.log(e.suppressed.name); \/\/ ErrorB\r\n    console.log(e.suppressed.message); \/\/ oops!\r\n}\r\n<\/code><\/pre>\n<p>You might have noticed that we&#8217;re using synchronous methods in these examples.\nHowever, lots of resource disposal involves <em>asynchronous<\/em> operations, and we need to wait for those to complete before we continue running any other code.<\/p>\n<p>That&#8217;s why there is also a new <code>Symbol.asyncDispose<\/code>, and it brings us to the next star of the show \u2014 <code>await using<\/code> declarations.\nThese are similar to <code>using<\/code> declarations, but the key is that they look up whose disposal must be <code>await<\/code>ed.\nThey use a different method named by <code>Symbol.asyncDispose<\/code>, though they can operate on anything with a <code>Symbol.dispose<\/code> as well.\nFor convenience, TypeScript also introduces a global type called <code>AsyncDisposable<\/code> that describes any object with an asynchronous dispose method.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>async function doWork() {\r\n    \/\/ Do fake work for half a second.\r\n    await new Promise(resolve => setTimeout(resolve, 500));\r\n}\r\n\r\nfunction loggy(id: string): AsyncDisposable {\r\n    console.log(`Constructing ${id}`);\r\n    return {\r\n        async [Symbol.asyncDispose]() {\r\n            console.log(`Disposing (async) ${id}`);\r\n            await doWork();\r\n        },\r\n    }\r\n}\r\n\r\nasync function func() {\r\n    await using a = loggy(\"a\");\r\n    await using b = loggy(\"b\");\r\n    {\r\n        await using c = loggy(\"c\");\r\n        await using d = loggy(\"d\");\r\n    }\r\n    await using e = loggy(\"e\");\r\n    return;\r\n\r\n    \/\/ Unreachable.\r\n    \/\/ Never created, never disposed.\r\n    await using f = loggy(\"f\");\r\n}\r\n\r\nfunc();\r\n\/\/ Constructing a\r\n\/\/ Constructing b\r\n\/\/ Constructing c\r\n\/\/ Constructing d\r\n\/\/ Disposing (async) d\r\n\/\/ Disposing (async) c\r\n\/\/ Constructing e\r\n\/\/ Disposing (async) e\r\n\/\/ Disposing (async) b\r\n\/\/ Disposing (async) a\r\n<\/code><\/pre>\n<p>Defining types in terms of <code>Disposable<\/code> and <code>AsyncDisposable<\/code> can make your code much easier to work with if you expect others to do tear-down logic consistently.\nIn fact, lots of existing types exist in the wild which have a <code>dispose()<\/code> or <code>close()<\/code> method.\nFor example, the Visual Studio Code APIs even define <a href=\"https:\/\/code.visualstudio.com\/api\/references\/vscode-api#Disposable\">their own <code>Disposable<\/code> interface<\/a>.\nAPIs in the browser and in runtimes like Node.js, Deno, and Bun might also choose to use <code>Symbol.dispose<\/code> and <code>Symbol.asyncDispose<\/code> for objects which already have clean-up methods, like file handles, connections, and more.<\/p>\n<p>Now maybe this all sounds great for libraries, but a little bit heavy-weight for your scenarios.\nIf you&#8217;re doing a lot of ad-hoc clean-up, creating a new type might introduce a lot of over-abstraction and questions about best-practices.\nFor example, take our <code>TempFile<\/code> example again.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>class TempFile implements Disposable {\r\n    #path: string;\r\n    #handle: number;\r\n\r\n    constructor(path: string) {\r\n        this.#path = path;\r\n        this.#handle = fs.openSync(path, \"w+\");\r\n    }\r\n\r\n    \/\/ other methods\r\n\r\n    [Symbol.dispose]() {\r\n        \/\/ Close the file and delete it.\r\n        fs.closeSync(this.#handle);\r\n        fs.unlinkSync(this.#path);\r\n    }\r\n}\r\n\r\nexport function doSomeWork() {\r\n    using file = new TempFile(\".some_temp_file\");\r\n\r\n    \/\/ use file...\r\n\r\n    if (someCondition()) {\r\n        \/\/ do some more work...\r\n        return;\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>All we wanted was to remember to call two functions \u2014 but was this the best way to write it?\nShould we be calling <code>openSync<\/code> in the constructor, create an <code>open()<\/code> method, or pass in the handle ourselves?\nShould we expose a method for every possible operation we need to perform, or should we just make the properties public?<\/p>\n<p>That brings us to the final stars of the feature: <code>DisposableStack<\/code> and <code>AsyncDisposableStack<\/code>.\nThese objects are useful for doing both one-off clean-up, along with arbitrary amounts of cleanup.\nA <code>DisposableStack<\/code> is an object that has several methods for keeping track of <code>Disposable<\/code> objects, and can be given functions for doing arbitrary clean-up work.\nWe can also assign them to <code>using<\/code> variables because \u2014 get this \u2014 <em>they&#8217;re also <code>Disposable<\/code><\/em>!\nSo here&#8217;s how we could&#8217;ve written the original example.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>function doSomeWork() {\r\n    const path = \".some_temp_file\";\r\n    const file = fs.openSync(path, \"w+\");\r\n\r\n    using cleanup = new DisposableStack();\r\n    cleanup.defer(() => {\r\n        fs.closeSync(file);\r\n        fs.unlinkSync(path);\r\n    });\r\n\r\n    \/\/ use file...\r\n\r\n    if (someCondition()) {\r\n        \/\/ do some more work...\r\n        return;\r\n    }\r\n\r\n    \/\/ ...\r\n}\r\n<\/code><\/pre>\n<p>Here, the <code>defer()<\/code> method just takes a callback, and that callback will be run once <code>cleanup<\/code> is disposed of.\nTypically, <code>defer<\/code> (and other <code>DisposableStack<\/code> methods like <code>use<\/code> and <code>adopt<\/code>)\nshould be called immediately after creating a resource.\nAs the name suggests, <code>DisposableStack<\/code> disposes of everything it keeps track of like a stack, in a first-in-last-out order, so <code>defer<\/code>ing immediately after creating a value helps avoid odd dependency issues.\n<code>AsyncDisposableStack<\/code> works similarly, but can keep track of <code>async<\/code> functions and <code>AsyncDisposable<\/code>s, and is itself an <code>AsyncDisposable.<\/code><\/p>\n<p>The <code>defer<\/code> method is similar in many ways to the <code>defer<\/code> keyword in <a href=\"https:\/\/go.dev\/tour\/flowcontrol\/12\">Go<\/a>, <a href=\"https:\/\/docs.swift.org\/swift-book\/documentation\/the-swift-programming-language\/statements\/#Defer-Statement\">Swift<\/a>, <a href=\"https:\/\/ziglang.org\/documentation\/master\/#defer\">Zig<\/a>, <a href=\"https:\/\/odin-lang.org\/docs\/overview\/#defer-statement\">Odin<\/a>, and others, where the conventions should be similar.<\/p>\n<p>Because this feature is so recent, most runtimes will not support it natively.\nTo use it, you will need runtime polyfills for the following:<\/p>\n<ul>\n<li><code>Symbol.dispose<\/code><\/li>\n<li><code>Symbol.asyncDispose<\/code><\/li>\n<li><code>DisposableStack<\/code><\/li>\n<li><code>AsyncDisposableStack<\/code><\/li>\n<li><code>SuppressedError<\/code><\/li>\n<\/ul>\n<p>However, if all you&#8217;re interested in is <code>using<\/code> and <code>await using<\/code>, you should be able to get away with only polyfilling the built-in <code>symbol<\/code>s.\nSomething as simple as the following should work for most cases:<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>Symbol.dispose ??= Symbol(\"Symbol.dispose\");\r\nSymbol.asyncDispose ??= Symbol(\"Symbol.asyncDispose\");\r\n<\/code><\/pre>\n<p>You will also need to set your compilation <code>target<\/code> to <code>es2022<\/code> or below, and configure your <code>lib<\/code> setting to either include <code>&quot;esnext&quot;<\/code> or <code>&quot;esnext.disposable&quot;<\/code>.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>{\r\n    \"compilerOptions\": {\r\n        \"target\": \"es2022\",\r\n        \"lib\": [\"es2022\", \"esnext.disposable\", \"dom\"]\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>For more information on this feature, <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/54505\">take a look at the work on GitHub<\/a>!<\/p>\n<h2>Decorator Metadata<\/h2>\n<p>TypeScript 5.2 implements <a href=\"https:\/\/github.com\/tc39\/proposal-decorator-metadata\">an upcoming ECMAScript feature called decorator metadata<\/a>.<\/p>\n<p>The key idea of this feature is to make it easy for decorators to create and consume metadata on any class they&#8217;re used on or within.<\/p>\n<p>Whenever decorator functions are used, they now have access to a new <code>metadata<\/code> property on their context object.\nThe <code>metadata<\/code> property just holds a simple object.\nSince JavaScript lets us add properties arbitrarily, it can be used as a dictionary that is updated by each decorator.\nAlternatively, since every <code>metadata<\/code> object will be identical for each decorated portion of a class, it can be used as a key into a <code>Map<\/code>.\nAfter all decorators on or in a class get run, that object can be accessed on the class via <code>Symbol.metadata<\/code>.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>interface Context {\r\n    name: string;\r\n    metadata: Record<PropertyKey, unknown>;\r\n}\r\n\r\nfunction setMetadata(_target: any, context: Context) {\r\n    context.metadata[context.name] = true;\r\n}\r\n\r\nclass SomeClass {\r\n    @setMetadata\r\n    foo = 123;\r\n\r\n    @setMetadata\r\n    accessor bar = \"hello!\";\r\n\r\n    @setMetadata\r\n    baz() { }\r\n}\r\n\r\nconst ourMetadata = SomeClass[Symbol.metadata];\r\n\r\nconsole.log(JSON.stringify(ourMetadata));\r\n\/\/ { \"bar\": true, \"baz\": true, \"foo\": true }\r\n<\/code><\/pre>\n<p>This can be useful in a number of different scenarios.\nMetadata could possibly be attached for lots of uses like debugging, serialization, or performing dependency injection with decorators.\nSince metadata objects are created per decorated class, frameworks can either privately use them as keys into a <code>Map<\/code> or <code>WeakMap<\/code>, or tack properties on as necessary.<\/p>\n<p>For example, let&#8217;s say we wanted to use decorators to keep track of which properties and accessors are serializable when using <code>JSON.stringify<\/code> like so:<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>import { serialize, jsonify } from \".\/serializer\";\r\n\r\nclass Person {\r\n    firstName: string;\r\n    lastName: string;\r\n\r\n    @serialize\r\n    age: number\r\n\r\n    @serialize\r\n    get fullName() {\r\n        return `${this.firstName} ${this.lastName}`;\r\n    }\r\n\r\n    toJSON() {\r\n        return jsonify(this)\r\n    }\r\n\r\n    constructor(firstName: string, lastName: string, age: number) {\r\n        \/\/ ...\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>Here, the intent is that only <code>age<\/code> and <code>fullName<\/code> should be serialized because they are marked with the <code>@serialize<\/code> decorator.\nWe define a <code>toJSON<\/code> method for this purpose, but it just calls out to <code>jsonify<\/code> which uses the metadata that <code>@serialize<\/code> created.<\/p>\n<p>Here&#8217;s an example of how the module <code>.\/serialize.ts<\/code> might be defined:<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>const serializables = Symbol();\r\n\r\ntype Context =\r\n    | ClassAccessorDecoratorContext\r\n    | ClassGetterDecoratorContext\r\n    | ClassFieldDecoratorContext\r\n    ;\r\n\r\nexport function serialize(_target: any, context: Context): void {\r\n    if (context.static || context.private) {\r\n        throw new Error(\"Can only serialize public instance members.\")\r\n    }\r\n    if (typeof context.name === \"symbol\") {\r\n        throw new Error(\"Cannot serialize symbol-named properties.\");\r\n    }\r\n\r\n    const propNames =\r\n        (context.metadata[serializables] as string[] | undefined) ??= [];\r\n    propNames.push(context.name);\r\n}\r\n\r\nexport function jsonify(instance: object): string {\r\n    const metadata = instance.constructor[Symbol.metadata];\r\n    const propNames = metadata?.[serializables] as string[] | undefined;\r\n    if (!propNames) {\r\n        throw new Error(\"No members marked with @serialize.\");\r\n    }\r\n\r\n    const pairStrings = propNames.map(key => {\r\n        const strKey = JSON.stringify(key);\r\n        const strValue = JSON.stringify((instance as any)[key]);\r\n        return `${strKey}: ${strValue}`;\r\n    });\r\n\r\n    return `{ ${pairStrings.join(\", \")} }`;\r\n}\r\n<\/code><\/pre>\n<p>This module has a local <code>symbol<\/code> called <code>serializables<\/code> to store and retrieve the names of properties marked <code>@serializable<\/code>.\nIt stores a list of these property names on the metadata on each invocation of <code>@serializable<\/code>.\nWhen <code>jsonify<\/code> is called, the list of properties is fetched off of the metadata and used to retrieve the actual values from the instance, eventually serializing those names and values.<\/p>\n<p>Using a <code>symbol<\/code> technically makes this data accessible to others.\nAn alternative might be to use a <code>WeakMap<\/code> using the metadata object as a key.\nThis keeps data private and happens to use fewer type assertions in this case, but is otherwise similar.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>const serializables = new WeakMap<object, string[]>();\r\n\r\ntype Context =\r\n    | ClassAccessorDecoratorContext\r\n    | ClassGetterDecoratorContext\r\n    | ClassFieldDecoratorContext\r\n    ;\r\n\r\nexport function serialize(_target: any, context: Context): void {\r\n    if (context.static || context.private) {\r\n        throw new Error(\"Can only serialize public instance members.\")\r\n    }\r\n    if (typeof context.name !== \"string\") {\r\n        throw new Error(\"Can only serialize string properties.\");\r\n    }\r\n\r\n    let propNames = serializables.get(context.metadata);\r\n    if (propNames === undefined) {\r\n        serializables.set(context.metadata, propNames = []);\r\n    }\r\n    propNames.push(context.name);\r\n}\r\n\r\nexport function jsonify(instance: object): string {\r\n    const metadata = instance.constructor[Symbol.metadata];\r\n    const propNames = metadata && serializables.get(metadata);\r\n    if (!propNames) {\r\n        throw new Error(\"No members marked with @serialize.\");\r\n    }\r\n    const pairStrings = propNames.map(key => {\r\n        const strKey = JSON.stringify(key);\r\n        const strValue = JSON.stringify((instance as any)[key]);\r\n        return `${strKey}: ${strValue}`;\r\n    });\r\n\r\n    return `{ ${pairStrings.join(\", \")} }`;\r\n}\r\n<\/code><\/pre>\n<p>As a note, these implementations don&#8217;t handle subclassing and inheritance.\nThat&#8217;s left as an exercise to you (and you might find that it is easier in one version of the file than the other!).<\/p>\n<p>Because this feature is still fresh, most runtimes will not support it natively.\nTo use it, you will need a polyfill for <code>Symbol.metadata<\/code>.\nSomething as simple as the following should work for most cases:<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>Symbol.metadata ??= Symbol(\"Symbol.metadata\");\r\n<\/code><\/pre>\n<p>You will also need to set your compilation <code>target<\/code> to <code>es2022<\/code> or below, and configure your <code>lib<\/code> setting to either include <code>&quot;esnext&quot;<\/code> or <code>&quot;esnext.decorators&quot;<\/code>.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>{\r\n    \"compilerOptions\": {\r\n        \"target\": \"es2022\",\r\n        \"lib\": [\"es2022\", \"esnext.decorators\", \"dom\"]\r\n    }\r\n}\r\n<\/code><\/pre>\n<p>We&#8217;d like to thank <a href=\"https:\/\/github.com\/a-tarasyuk\">Oleksandr Tarasiuk<\/a> for contributing <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/54657\">the implementation of decorator metadata<\/a> for TypeScript 5.2!<\/p>\n<p><!-- TODO: Why is there a conditional type around the existence of `Symbol.metadata`? --><\/p>\n<h2>Named and Anonymous Tuple Elements<\/h2>\n<p>Tuple types have supported optional labels or names for each element.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>type Pair<T> = [first: T, second: T];\r\n<\/code><\/pre>\n<p>These labels don&#8217;t change what you&#8217;re allowed to do with them \u2014 they&#8217;re solely to help with readability and tooling.<\/p>\n<p>However, TypeScript previously had a rule that tuples could not mix and match between labeled and unlabeled elements.\nIn other words, either no element could have a label in a tuple, or all elements needed one.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>\/\/ \u2705 fine - no labels\r\ntype Pair1<T> = [T, T];\r\n\r\n\/\/ \u2705 fine - all fully labeled\r\ntype Pair2<T> = [first: T, second: T];\r\n\r\n\/\/ \u274c previously an error\r\ntype Pair3<T> = [first: T, T];\r\n\/\/                         ~\r\n\/\/ Tuple members must all have names\r\n\/\/ or all not have names.\r\n<\/code><\/pre>\n<p>This could be annoying for rest elements where we&#8217;d be forced to just add a label like <code>rest<\/code> or <code>tail<\/code>.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>\/\/ \u274c previously an error\r\ntype TwoOrMore_A<T> = [first: T, second: T, ...T[]];\r\n\/\/                                          ~~~~~~\r\n\/\/ Tuple members must all have names\r\n\/\/ or all not have names.\r\n\r\n\/\/ \u2705\r\ntype TwoOrMore_B<T> = [first: T, second: T, rest: ...T[]];\r\n<\/code><\/pre>\n<p>It also meant that this restriction had to be enforced internally in the type system, meaning TypeScript would lose labels.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>type HasLabels = [a: string, b: string];\r\ntype HasNoLabels = [number, number];\r\ntype Merged = [...HasNoLabels, ...HasLabels];\r\n\/\/   ^ [number, number, string, string]\r\n\/\/\r\n\/\/     'a' and 'b' were lost in 'Merged'\r\n<\/code><\/pre>\n<p>In TypeScript 5.2, the all-or-nothing restriction on tuple labels has been lifted.\nThe language can now also preserve labels when spreading into an unlabeled tuple.<\/p>\n<p>We&#8217;d like to extend our thanks to <a href=\"https:\/\/github.com\/JoshuaKGoldberg\">Josh Goldberg<\/a> and <a href=\"https:\/\/github.com\/Andarist\">Mateusz Burzy\u0144ski<\/a> who <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/53356\">collaborated to lift this restriction<\/a>.<\/p>\n<h2>Easier Method Usage for Unions of Arrays<\/h2>\n<p>In previous versions on TypeScript, calling a method on a union of arrays could end in pain.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>declare let array: string[] | number[];\r\n\r\narray.filter(x => !!x);\r\n\/\/    ~~~~~~ error!\r\n\/\/ This expression is not callable.\r\n\/\/   Each member of the union type '...' has signatures,\r\n\/\/   but none of those signatures are compatible\r\n\/\/   with each other.\r\n<\/code><\/pre>\n<p>In this example, TypeScript would try to see if each version of <code>filter<\/code> is compatible across <code>string[]<\/code> and <code>number[]<\/code>.\nWithout a coherent strategy, TypeScript threw its hands in the air and said &quot;I can&#8217;t make it work&quot;.<\/p>\n<p>In TypeScript 5.2, before giving up in these cases, unions of arrays are treated as a special case.\nA new array type is constructed out of each member&#8217;s element type, and then the method is invoked on that.<\/p>\n<p>Taking the above example, <code>string[] | number[]<\/code> is transformed into <code>(string | number)[]<\/code> (or <code>Array&lt;string | number&gt;<\/code>), and <code>filter<\/code> is invoked on that type.\nThere is a slight caveat which is that <code>filter<\/code> will produce an <code>Array&lt;string | number&gt;<\/code> instead of a <code>string[] | number[]<\/code>;\nbut for a freshly produced value there is less risk of something &quot;going wrong&quot;.<\/p>\n<p>This means lots of methods like <code>filter<\/code>, <code>find<\/code>, <code>some<\/code>, <code>every<\/code>, and <code>reduce<\/code> should all be invokable on unions of arrays in cases where they were not previously.<\/p>\n<p>You can <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/53489\">read up more details on the implementing pull request<\/a>.<\/p>\n<h2>Copying Array Methods<\/h2>\n<p>TypeScript 5.2 includes definitions for the methods added to ECMAScript in the <a href=\"https:\/\/github.com\/tc39\/proposal-change-array-by-copy\">&quot;Change Array by Copy&quot;<\/a> proposal.<\/p>\n<p>While JavaScript&#8217;s <code>Array<\/code>s already had several useful methods like <code>sort()<\/code>, <code>splice()<\/code>, and <code>reverse()<\/code>, these methods updated the current array in-place.\nOften, it&#8217;s desirable to create a completely separate array without affecting the original.\nTo do this, you could use <code>slice()<\/code> or an array spread (like <code>[...myArray]<\/code>) to get a copy first, and then perform the operation.\nFor example, you could get a reversed copy by writing <code>myArray.slice().reverse()<\/code>.<\/p>\n<p>There is also another common case &#8211; creating a copy, but with a single element changed.\nThere are a number of ways of doing this, but the most obvious ones either are multiple statements long&#8230;<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>const copy = myArray.slice();\r\ncopy[someIndex] = updatedValue;\r\ndoSomething(copy);\r\n<\/code><\/pre>\n<p>&#8230;or are not obvious in intent.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>doSomething(myArray.map((value, index) => index === someIndex ? updatedValue : value));\r\n<\/code><\/pre>\n<p>All of this is cumbersome for operations that are so common.\nThat&#8217;s why JavaScript now has 4 new methods which perform the same operations, but which don&#8217;t affect the original data: <code>toSorted<\/code>, <code>toSpliced<\/code>, <code>toReversed<\/code>, and <code>with<\/code>.\nThe first 3 methods perform the same operation as their mutating counterparts, but return a new array.\n<code>with<\/code> also returns a new array, but with a single element updated (as described above).<\/p>\n<table>\n<thead>\n<tr>\n<th>Mutating<\/th>\n<th>Copying<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>myArray.reverse()<\/code><\/td>\n<td><code>myArray.toReversed()<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>myArray.sort((a, b) =&gt; ...)<\/code><\/td>\n<td><code>myArray.toSorted((a, b) =&gt; ...)<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>myArray.splice(start, deleteCount, ...items)<\/code><\/td>\n<td><code>myArray.toSpliced(start, deleteCount, ...items)<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>myArray[index] = updatedValue<\/code><\/td>\n<td><code>myArray.with(index, updatedValue)<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Note that the copying methods <em>always<\/em> create a new array, whereas the mutating operations are inconsistent.<\/p>\n<p>These methods aren&#8217;t just available on plain <code>Array<\/code>s &#8211; they&#8217;re also available on <code>TypedArray<\/code>s like <code>Int32Array<\/code>, <code>Uint8Array<\/code>, etc.<\/p>\n<p>We&#8217;d like to thank <a href=\"https:\/\/github.com\/sno2\">Carter Snook<\/a> who provided <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/51367\">the updates for these declarations<\/a>.<\/p>\n<h2><code>symbol<\/code>s as <code>WeakMap<\/code> and <code>WeakSet<\/code> Keys<\/h2>\n<p><code>symbol<\/code>s can now be used as keys in a <code>WeakMap<\/code>s and <code>WeakSet<\/code>s, reflecting <a href=\"https:\/\/github.com\/tc39\/proposal-symbols-as-weakmap-keys\">the addition of this feature to ECMAScript itself<\/a>.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>const myWeakMap = new WeakMap<symbol, object>();\r\n\r\nconst key = Symbol();\r\nconst someObject = { \/*...*\/ };\r\n\r\n\/\/ Works! \u2705\r\nmyWeakMap.set(key, someObject);\r\nmyWeakMap.has(key);\r\n<\/code><\/pre>\n<p><a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/54195\">This update<\/a> was provided by <a href=\"https:\/\/github.com\/leoelm\">Leo Elmecker-Plakolm<\/a> on the behalf of Bloomberg.\nWe&#8217;d like to extend our thanks to them!<\/p>\n<h2>Type-Only Import Paths with TypeScript Implementation File Extensions<\/h2>\n<p>TypeScript now allows both declaration <em>and<\/em> implementation file extensions to be included in type-only import paths, regardless of whether <code>allowImportingTsExtensions<\/code> is enabled.<\/p>\n<p>This means that you can now write <code>import type<\/code> statements that use <code>.ts<\/code>, <code>.mts<\/code>, <code>.cts<\/code>, and <code>.tsx<\/code> file extensions.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>import type { JustAType } from \".\/justTypes.ts\";\r\n\r\nexport function f(param: JustAType) {\r\n    \/\/ ...\r\n}\r\n<\/code><\/pre>\n<p>It also means that <code>import()<\/code> types, which can be used in both TypeScript and JavaScript with JSDoc, can use those file extensions.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>\/**\r\n * @param {import(\".\/justTypes.ts\").JustAType} param\r\n *\/\r\nexport function f(param) {\r\n    \/\/ ...\r\n}\r\n<\/code><\/pre>\n<p>For more information, <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/54746\">see the change here<\/a>.<\/p>\n<h2>Comma Completions for Object Members<\/h2>\n<p>It can be easy to forget to add a comma when adding a new property to an object.\nPreviously, if you forgot a comma and requested auto-completion, TypeScript would confusingly give poor unrelated completion results.<\/p>\n<p>TypeScript 5.2 now gracefully provides object member completions when you&#8217;re missing a comma.\nBut to just skip past hitting you with a syntax error, it will <em>also<\/em> auto-insert the missing comma.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/typescript\/wp-content\/uploads\/sites\/11\/2023\/06\/comma-completions-5-2-beta.gif\" alt=\"Properties in an object literal are completed despite missing a comma after a prior property. When the property name is completed, the missing comma is automatically inserted.\"><\/p>\n<p>For more information, <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/52899\">see the implementation here<\/a>.<\/p>\n<h2>Inline Variable Refactoring<\/h2>\n<p>TypeScript 5.2 now has a refactoring to inline the contents of a variable to all usage sites.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/typescript\/wp-content\/uploads\/sites\/11\/2023\/06\/inline-variable-5-2-beta.gif\" alt=\"A variable called 'path' initialized to a string, having both of its usages replaced\">.<\/p>\n<p>Using the &quot;inline variable&quot; refactoring will eliminate the variable and replace all the variable&#8217;s usages with its initializer.\nNote that this may cause that initializer&#8217;s side-effects to run at a different time, and as many times as the variable has been used.<\/p>\n<p>For more details, <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/54281\">see the implementing pull request<\/a>.<\/p>\n<h2>Clickable Inlay Parameter Hints<\/h2>\n<p>Inlay hints can provide us with information at a glance, even if it doesn&#8217;t exist within our code &#8211; think parameter names, inferred types, and more.\nIn TypeScript 5.2, we&#8217;ve begun to make it possible to interact with inlay hints.\nFor example, Visual Studio Code Insiders, you can now click on inlay hints to jump to the definitions of parameters.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/typescript\/wp-content\/uploads\/sites\/11\/2023\/08\/clickable-inlay-hints-5-2.gif\" alt=\"Ctrl-clickable or Cmd-clickable parameter inlay hints which will jump you to their definition\"><\/p>\n<p>For more information, you can <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/54734\">take a peek at the implementation of this feature here<\/a>.<\/p>\n<h2>Optimized Checks for Ongoing Type Compatibility<\/h2>\n<p>Because TypeScript is a structural type system, types occasionally need to be compared in a member-wise fashion;\nhowever, recursive types add some issues here.\nFor example:<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>interface A {\r\n    value: A;\r\n    other: string;\r\n}\r\n\r\ninterface B {\r\n    value: B;\r\n    other: number;\r\n}\r\n<\/code><\/pre>\n<p>When checking whether the type <code>A<\/code> is compatible with the type <code>B<\/code>, TypeScript will end up checking whether the types of <code>value<\/code> in <code>A<\/code> and <code>B<\/code> are respectively compatible.\nAt this point, the type system needs to stop checking any further and proceed to check other members.\nTo do this, the type system has to track when any two types are already being related.<\/p>\n<p>Previously TypeScript already kept a stack of type pairs, and iterated through that to determine whether those types are being related.\nWhen this stack is shallow that&#8217;s not a problem; but when the stack isn&#8217;t shallow, that, uh, <a href=\"https:\/\/accidentallyquadratic.tumblr.com\/\">is a problem<\/a>.<\/p>\n<p>In TypeScript 5.2, a simple <code>Set<\/code> helps tracks this information.\nThis reduced the time spent on a reported test case that used the <a href=\"https:\/\/github.com\/drizzle-team\/drizzle-orm\">drizzle<\/a> library by over 33%!<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>Benchmark 1: old\r\n  Time (mean \u00b1 \u03c3):      3.115 s \u00b1  0.067 s    [User: 4.403 s, System: 0.124 s]\r\n  Range (min \u2026 max):    3.018 s \u2026  3.196 s    10 runs\r\n\r\nBenchmark 2: new\r\n  Time (mean \u00b1 \u03c3):      2.072 s \u00b1  0.050 s    [User: 3.355 s, System: 0.135 s]\r\n  Range (min \u2026 max):    1.985 s \u2026  2.150 s    10 runs\r\n\r\nSummary\r\n  'new' ran\r\n    1.50 \u00b1 0.05 times faster than 'old'\r\n<\/code><\/pre>\n<p><a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/55224\">Read more on the change here<\/a>.<\/p>\n<h2>Breaking Changes and Correctness Fixes<\/h2>\n<p>TypeScript strives not to unnecessarily introduce breaks;\nhowever, occasionally we must make corrections and improvements so that code can be better-analyzed.<\/p>\n<h2><code>lib.d.ts<\/code> Changes<\/h2>\n<p>Types generated for the DOM may have an impact on your codebase.\nFor more information, <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/54725\">see the DOM updates for TypeScript 5.2<\/a>.<\/p>\n<h2><code>labeledElementDeclarations<\/code> May Hold <code>undefined<\/code> Elements<\/h2>\n<p>In order <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/53356\">to support a mixture of labeled and unlabeled elements<\/a>, TypeScript&#8217;s API has changed slightly.\nThe <code>labeledElementDeclarations<\/code> property of <code>TupleType<\/code> may hold <code>undefined<\/code> for at each position where an element is unlabeled.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>  interface TupleType {\r\n-     labeledElementDeclarations?: readonly (NamedTupleMember | ParameterDeclaration)[];\r\n+     labeledElementDeclarations?: readonly (NamedTupleMember | ParameterDeclaration | undefined)[];\r\n  }\r\n<\/code><\/pre>\n<h2><code>module<\/code> and <code>moduleResolution<\/code> Must Match Under Recent Node.js settings<\/h2>\n<p>The <code>--module<\/code> and <code>--moduleResolution<\/code> options each support a <code>node16<\/code> and <code>nodenext<\/code> setting.\nThese are effectively &quot;modern Node.js&quot; settings that should be used on any recent Node.js project.\nWhat we&#8217;ve found is that when these two options don&#8217;t agree on whether they are using Node.js-related settings, projects are effectively misconfigured.<\/p>\n<p>In TypeScript 5.2, when using <code>node16<\/code> or <code>nodenext<\/code> for either of the <code>--module<\/code> and <code>--moduleResolution<\/code> options, TypeScript now requires the other to have a similar Node.js-related setting.\nIn cases where the settings diverge, you&#8217;ll likely get an error message like either<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>Option 'moduleResolution' must be set to 'NodeNext' (or left unspecified) when option 'module' is set to 'NodeNext'.\r\n<\/code><\/pre>\n<p>or<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>Option 'module' must be set to 'Node16' when option 'moduleResolution' is set to 'Node16'.\r\n<\/code><\/pre>\n<p>So for example <code>--module esnext --moduleResolution node16<\/code> will be rejected \u2014 but you may be better off just using <code>--module nodenext<\/code> alone, or <code>--module esnext --moduleResolution bundler<\/code>.<\/p>\n<p>For more information, <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/54567\">see the change here<\/a>.<\/p>\n<h2>Consistent Export Checking for Merged Symbols<\/h2>\n<p>When two declarations merge, they must agree in whether they are both exported.\nDue to a bug, TypeScript missed specific cases in ambient contexts, like in declaration files or <code>declare module<\/code> blocks.\nFor example, it would not issue an error on a case like the following, where <code>replaceInFile<\/code> is declared once as an exported function, and one as an un-exported namespace.<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>declare module 'replace-in-file' {\r\n    export function replaceInFile(config: unknown): Promise<unknown[]>;\r\n    export {};\r\n\r\n    namespace replaceInFile {\r\n        export function sync(config: unknown): unknown[];\r\n  }\r\n}\r\n<\/code><\/pre>\n<p>In an ambient module, adding an <code>export { ... }<\/code> or a similar construct like <code>export default ...<\/code> implicitly changes whether all declarations are automatically exported.\nTypeScript now recognizes these unfortunately confusing semantics more consistently, and issues an error on the fact that all declarations of <code>replaceInFile<\/code> need to agree in their modifiers, and will issue the following error:<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>Individual declarations in merged declaration 'replaceInFile' must be all exported or all local.\r\n<\/code><\/pre>\n<p>For more information, <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/54659\">see the change here<\/a>.<\/p>\n<h2><code>module<\/code>s Always Emits as <code>namespace<\/code><\/h2>\n<p>TypeScript&#8217;s <code>namespace<\/code>s actually started out using the <code>module<\/code> keyword, as it appeared that ECMAScript might end up using it for the same purpose.\nOriginally, these were called &quot;internal modules&quot;, but internal modules never ended up making it into JavaScript.<\/p>\n<p>For many years (since <a href=\"https:\/\/devblogs.microsoft.com\/typescript\/announcing-typescript-1-5\">TypeScript 1.5 from 2015<\/a>!), TypeScript has supported the <code>namespace<\/code> keyword to avoid confusion.\nAs a way to take this further, TypeScript 5.2 will always emit the <code>namespace<\/code> keyword when generating declaration files.\nSo code like the following:<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>module foo {\r\n    export function f() {}\r\n}\r\n<\/code><\/pre>\n<p>will result in the following declaration file:<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>declare namespace foo {\r\n    function f(): void;\r\n}\r\n<\/code><\/pre>\n<p>While this may be incompatible with much much older versions of TypeScript, we believe the impact should be limited.<\/p>\n<p>Note that ambient module declarations like the following<\/p>\n<pre class=\"lang:default decode:true\" style=\"padding: 10px;border-radius: 10px;\"><code>\/\/ UNAFFECTED\r\ndeclare module \"some-module-path\" {\r\n    \/\/ ...\r\n}\r\n<\/code><\/pre>\n<p>are unaffected.<\/p>\n<p><a href=\"https:\/\/github.com\/microsoft\/TypeScript\/pull\/54134\">This work<\/a> was provided courtesy of <a href=\"https:\/\/github.com\/CC972\">Chi Leung<\/a> on the behalf of Bloomberg.<\/p>\n<h2>What&#8217;s Next?<\/h2>\n<p>To get a sense of what&#8217;s next, you can take a look at the <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/issues\/55486\">TypeScript 5.3 Iteration Plan<\/a>.\nIt should give you the details you need to plan around our next release, and what to expect from it.<\/p>\n<p>If you want to try out the current state of TypeScript 5.3, you can <a href=\"https:\/\/www.typescriptlang.org\/docs\/handbook\/nightly-builds.html\">try a nightly build<\/a>.\nOur nightlies are well-tested and can even be used <a href=\"https:\/\/marketplace.visualstudio.com\/items?itemName=ms-vscode.vscode-typescript-next\">solely in your editor<\/a>.<\/p>\n<p>Otherwise, we hope that TypeScript 5.2 makes your day-to-day coding a joy.<\/p>\n<p>Happy Hacking!<\/p>\n<p>&#8211; Daniel Rosenwasser and the TypeScript Team<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Today we&#8217;re excited to announce the release of TypeScript 5.2! If you&#8217;re not familiar with TypeScript, it&#8217;s a language that builds on top of JavaScript by making it possible to declare and describe types. Writing types in our code allows us to explain intent and have other tools check our code to catch mistakes like [&hellip;]<\/p>\n","protected":false},"author":381,"featured_media":1797,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-4017","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-typescript"],"acf":[],"blog_post_summary":"<p>Today we&#8217;re excited to announce the release of TypeScript 5.2! If you&#8217;re not familiar with TypeScript, it&#8217;s a language that builds on top of JavaScript by making it possible to declare and describe types. Writing types in our code allows us to explain intent and have other tools check our code to catch mistakes like [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/posts\/4017","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/users\/381"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/comments?post=4017"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/posts\/4017\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/media\/1797"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/media?parent=4017"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/categories?post=4017"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/typescript\/wp-json\/wp\/v2\/tags?post=4017"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}