Earlier this year, the TypeScript team announced that we’ve been porting the compiler and language service to native code to take advantage of better raw performance, memory usage, and parallelism. This effort (codenamed “Project Corsa”, and soon “TypeScript 7.0”) has been a significant undertaking, but we’ve made big strides in the past few months. We’re […]
The post Progress on TypeScript 7 – December 2025 appeared first on TypeScript.
]]>Earlier this year, the TypeScript team announced that we’ve been porting the compiler and language service to native code to take advantage of better raw performance, memory usage, and parallelism. This effort (codenamed “Project Corsa”, and soon “TypeScript 7.0”) has been a significant undertaking, but we’ve made big strides in the past few months. We’re excited to give some updates on where we are, and show you how “real” the new TypeScript toolset is today.
We also have news about our upcoming roadmap, and how we’re prioritizing work on TypeScript 7.0 to drive our port to completion.
For a lot of developers, a project rewrite might feel entirely theoretical until it’s finally released. That’s not the case here.
TypeScript’s native previews are fast, stable, and easy to use today – including in your editor.
TypeScript’s language service (the thing that powers your editor’s TypeScript and JavaScript features) is also a core part of the native port effort, and is easy to try out. You can grab the latest version from the Visual Studio Code Marketplace which gets updated every day.
Our team is still porting features and fixing minor bugs, but most of what really makes the existing TypeScript editing experience is there and working well.
That includes:
You might notice a few things that stand out since our last major update – auto-imports, find-all-references, rename, and more. We know that these features were the missing pieces that held a lot of developers back from trying out the native previews. We’re happy to say that these are now reimplemented and ready for day-to-day use! These operations now work in any TypeScript or JavaScript codebase – including those with project references.
We’ve also rearchitected parts of our language service to improve reliability while also leveraging shared-memory parallelism. While some teams reported the original experience was a bit “crashy” at times, they often put up with it because of the speed improvements. The new architecture is more robust, and should be able to handle codebases, both big and small, without issues.
While there is certainly more to port and polish, your team will likely find that trying out TypeScript’s native previews is worth it. You can expect faster load times, less memory usage, and a more snappy/responsive editor on the whole.
If you’re ever unhappy with the experience, our extension makes it easy to toggle between VS Code’s built-in TypeScript experience and the new one. We really encourage you and your team to try out the native preview extension for VS Code today!
The TypeScript compiler has also made significant progress in the native port.
Just like our VS Code extension, we have been publishing nightly preview builds of the new compiler under the package name @typescript/native-preview.
You can install it via npm like so:
# local dev dependency
npm install -D @typescript/native-preview
# global install
npm install -g @typescript/native-preview
This package provides a tsgo command that works similarly to the existing tsc command.
The two can be run side-by-side.
A frequent question we get is whether it’s “safe” to use TypeScript 7 to validate a build; in other words, does it reliably find the same errors that TypeScript 5.9 does?
The answer is a resounding yes.
TypeScript 7’s type-checking is very nearly complete.
For context, we have around 20,000 compiler test cases, of which about 6,000 produce at least one error in TypeScript 6.0. In all but 74 cases, TypeScript 7 also produces at least one error.
Of those remaining 74 cases, all are known incomplete work (e.g. regular expression syntax checking or isolatedDeclarations errors) or are related to known intentional changes (deprecations, default settings changes, etc.).
You can confidently use TypeScript 7 today to type-check your project for errors.
Beyond single-pass/single-project type checking, the command-line compiler has reached major parity as well.
Features like --incremental, project reference support, and --build mode are also now all ported over and working!
This means most projects can now try the native preview with minimal changes.
# Running tsc in --build mode...
tsc -b some.tsconfig.json --extendedDiagnostics
# Running the *new compiler* in --build mode...
tsgo -b some.tsconfig.json --extendedDiagnostics
Not only are these features now available, they should be dramatically faster than the existing versions implemented in TypeScript 5.9 and older (a.k.a. the “Strada codebase”).
As we’ve described previously, this comes in part from native code performance, but also from the use of shared-memory parallelism.
More specifically what this means is that not only can TypeScript now do fast multi-threaded builds on single projects;
it can now build up multiple projects in parallel as well!
Combined with our reimplementation of --incremental, we’re close to making TypeScript builds feel instantaneous for smaller changes in large projects.
Just as a reminder, even without --incremental, TypeScript 7 often sees close to a 10x speedup over the 6.0 compiler on full builds!
| Project | tsc (6.0) | tsgo (7.0) | Delta | Speedup Factor |
|---|---|---|---|---|
| sentry | 133.08s | 16.25s | 116.84s | 8.19x |
| vscode | 89.11s | 8.74s | 80.37s | 10.2x |
| typeorm | 15.80s | 1.06s | 14.20s | 9.88x |
| playwright | 9.30s | 1.24s | 8.07s | 7.51x |
There are some caveats to using the new compiler that we want to call out. Many of these are point-in-time issues that we plan to resolve before the final 7.0 release, but some are driven more by long-term decisions to make the default TypeScript experience better. The promise of TypeScript 7.0 means that we will need to heavily shift our focus to the new codebase to close existing gaps and put the new toolchain in the hands of more developers. But let’s first dive in and cover some of the current changes and limitations.
TypeScript 7.0 will remove behaviors and flags that we plan to deprecate in TypeScript 6.0. Right now, you can see the list of upcoming deprecations in 6.0 on our issue tracker. Some prominent examples include:
--strict will be enabled by default--target will default to the latest stable ECMAScript target (e.g. es2025)--target es5 will be removed, with es2015 being the lowest-supported target--baseUrl will be removed--moduleResolution node10 (a.k.a. node) will be removed in favor of bundler and nodenextrootDir defaults to the current directory, and using outDir either requires an explicit rootDir or for top-level source files to be in the same directory as the tsconfig.jsonThis is not comprehensive, so check out the issue tracker for the current state of things.
If your project relies on any of these deprecated behaviors, you may need to make some changes to your codebase or tsconfig.json to ensure compatibility with TypeScript 7.0.
Our team has been experimenting with a tool called ts5to6 to help update your tsconfig.json automatically.
The tool uses heuristics on extends and references to help update other projects in your codebase.
Currently it can only update the baseUrl and rootDir settings, but more may be added in the future.
npx @andrewbranch/ts5to6 --fixBaseUrl your-tsconfig-file-here.json
npx @andrewbranch/ts5to6 --fixRootDir your-tsconfig-file-here.json
--watch, and APIEven with 6.0-readiness, there are some circumstances in which the new compiler can’t immediately be swapped in.
For one, the JavaScript emit pipeline is not entirely complete.
If you don’t need JavaScript emit from TypeScript (e.g. if you use Babel, esbuild, or something else), or if you are targeting modern browsers/runtimes, running tsgo for your build will work just fine.
But if you rely on the TypeScript to target older runtimes, our support for downlevel compilation realistically only goes as far back the es2021 target, and with no support for compiling decorators.
We plan to address this with full --target support going back to es2015, but that work is still ongoing.
Another issue is that our new --watch mode may be less-efficient than the existing TypeScript compiler in some scenarios.
In some cases you can find other solutions like running nodemon and tsgo with the --incremental flag.
Finally, Corsa/TypeScript 7.0 will not support the existing Strada API. The Corsa API is still a work in progress, and no stable tooling integration exists for it. That means any tools like linters, formatters, or IDE extensions that rely on the Strada API will not work with Corsa.
The workaround for some of these issues may be to have the typescript and @typescript/native-preview packages installed side-by-side, and use the ≤6.0 API for tooling that needs it, with tsgo for type-checking.
Another thing that we want to call out is that our JavaScript type-checking support (partly powered by JSDoc annotations) has been rewritten from the ground up.
In an effort to simplify our internals, we have stripped down some of our support for complex and some less-used patterns that we previously recognized and analyzed.
For example, TypeScript 7.0 does not recognize the @enum and @constructor tags.
We also dropped some “relaxed” type-checking rules in JavaScript, such as interpreting:
Object as any,String as string,Foo as typeof Foo when the latter would have been valid in a TypeScript file,any, unknown, and undefined-typed parameters as optionaland more. Some of these are being reviewed and documented here, though the list may need to be updated.
This means that some JavaScript codebases may see more errors than they did before, and may need to be updated to work well with the new compiler. On the flip side, we believe that the new implementation is more robust and maintainable, and aligns TypeScript’s JSDoc support with its own type syntax.
If you feel like something should be working or is missing from our JavaScript type-checking support, we encourage you to file an issue on our GitHub repository.
When we set out to rewrite TypeScript last year, there were a lot of uncertainties. Would the community be excited? How long would it take for the codebase to stabilize? How quickly could teams adopt this new toolset? What degree of compatibility would we be able to deliver?
On all fronts, we’ve been very pleasantly surprised. We’ve been able to implement a type-checker with extremely high compatibility. As a result, projects both inside and outside Microsoft report that they’ve been able to easily use the native compiler with minimal effort. Stability is going well, and we’re on track to finish most language service features by the end of the year. Many teams are already using Corsa for day-to-day work without any blocking issues.
With 6.0 around the corner, we have to consider what happens next in the JavaScript codebase. Our initial plan was to continue work in the 6.0 line “until TypeScript 7+ reaches sufficient maturity and adoption”. We know there is still remaining work to do to unblock more developers (e.g. more work on the API surface), and closing down development on the Strada line – our JavaScript-based compiler – is the best way for us to get those blockers removed sooner rather than later. To help us get these done as soon as possible, we’re taking a few steps in the Strada project.
TypeScript 6.0 will be our last release based on the existing TypeScript/JavaScript codebase. In other words, we do not intend to release a TypeScript 6.1, though we may have patch releases (e.g. 6.0.1, 6.0.2) under rarer circumstances.
You can think of TypeScript 6.0 as a “bridge” release between TypeScript 5.9 line and 7.0. 6.0 will deprecate features to align with 7.0, and will be highly compatible in terms of type-checking behavior.
Most codebases which need editor-side Strada-specific functionality (e.g. language service plugins) should be able to use 6.0 for editor functionality, and 7.0 for fast command-line builds without much trouble. The inverse is also true: developers can use 7.0 for a faster experience in their editor, and 6.0 for command-line tooling that relies on the TypeScript 6.0 API.
Additional servicing after TypeScript 6.0 is released will be in the form of patch releases, and will only be issued in the case of:
As with previous releases, patch releases will be infrequent, and only issued when absolutely necessary.
But as for right now, we want to ensure that TypeScript 6.0 and 7.0 are as compatible as possible. We’ll be holding a very high bar in terms of which open PRs are merged into the 6.0 line. That takes effect today, and it means most developers will have to set expectations for which issues will be addressed in TypeScript 6.0. Additionally, contributors should understand that we are very unlikely to merge pull requests into 6.0, with most of our focus going bringing 7.0 to parity and stability. We want to be transparent on this front so that there is no “wasted” work, and so that our team can avoid complications in porting changes between the two codebases.
While most of the core type-checking code has been ported over without any behavioral differences, the language service is a different story. Given the new architecture, much of the code that powers completions, hover tooltips, navigation, and more, has been heavily rewritten. Additionally, TypeScript 7.0 uses the standard LSP protocol instead of the custom TSServer protocol, so some behavior specific to the TypeScript VS Code Extension may have changed.
As a result, any bugs or suggestions specific to language service behavior are likely not to reproduce in the 7.0 line, or need a “reset” in the conversation.
These issues are very time-consuming to manually verify, so instead we’ll be closing existing issues related to language service behavior. If you run into an issue that was closed under the “7.0 LS Migration” label, please log a new issue after validating that it can be reproduced in the native nightly extension. For functionality that is not yet ported to 7.0, please wait until that functionality is present before raising a new issue.
When we unveiled our native previews a few months back, we had to manage expectations on the state of the project. We’re now at the point where we can confidently say that the native TypeScript experience is real, stable, and ready for broader use. But we are absolutely still looking for feedback.
So we encourage you to install the VS Code native preview extension, use the @typescript/native-preview compiler package where you can, and try it out in your projects.
Let us know what you think, and file issues on our GitHub repository to help us fix up any issues and prioritize what to work on next.
We’re excited about the future of TypeScript, and we can’t wait to get TypeScript 7.0 into your hands!
Happy Hacking!
The post Progress on TypeScript 7 – December 2025 appeared first on TypeScript.
]]>Today we are excited to announce the release of TypeScript 5.9! If you’re not familiar with TypeScript, it’s a language that builds on JavaScript by adding syntax for types. With types, TypeScript makes it possible to check your code to avoid bugs ahead of time. The TypeScript type-checker does all this, and is also the […]
The post Announcing TypeScript 5.9 appeared first on TypeScript.
]]>Today we are excited to announce the release of TypeScript 5.9!
If you’re not familiar with TypeScript, it’s a language that builds on JavaScript by adding syntax for types. With types, TypeScript makes it possible to check your code to avoid bugs ahead of time. The TypeScript type-checker does all this, and is also the foundation of great tooling in your editor and elsewhere, making coding even easier. If you’ve written JavaScript in editors like Visual Studio and VS Code, TypeScript even powers features you might already be using like completions, go-to-definition, and more. You can learn more about TypeScript at our website.
But if you’re already familiar, you can start using TypeScript 5.9 today!
npm install -D typescript
Let’s take a look at what’s new in TypeScript 5.9!
tsc --initimport defer--module node20There have been no changes to TypeScript 5.9 since the release candidate.
A few fixes for reported issues have been made since the 5.9 beta, including the restoration of AbortSignal.abort() to the DOM library.
Additionally, we have added a section about Notable Behavioral Changes.
tsc --initFor a while, the TypeScript compiler has supported an --init flag that can create a tsconfig.json within the current directory.
In the last few years, running tsc --init created a very “full” tsconfig.json, filled with commented-out settings and their descriptions.
We designed this with the intent of making options discoverable and easy to toggle.
However, given external feedback (and our own experience), we found it’s common to immediately delete most of the contents of these new tsconfig.json files.
When users want to discover new options, we find they rely on auto-complete from their editor, or navigate to the tsconfig reference on our website (which the generated tsconfig.json links to!).
What each setting does is also documented on that same page, and can be seen via editor hovers/tooltips/quick info.
While surfacing some commented-out settings might be helpful, the generated tsconfig.json was often considered overkill.
We also felt that it was time that tsc --init initialized with a few more prescriptive settings than we already enable.
We looked at some common pain points and papercuts users have when they create a new TypeScript project.
For example, most users write in modules (not global scripts), and --moduleDetection can force TypeScript to treat every implementation file as a module.
Developers also often want to use the latest ECMAScript features directly in their runtime, so --target can typically be set to esnext.
JSX users often find that going back to set --jsx is needless friction, and its options are slightly confusing.
And often, projects end up loading more declaration files from node_modules/@types than TypeScript actually needs; but specifying an empty types array can help limit this.
In TypeScript 5.9, a plain tsc --init with no other flags will generate the following tsconfig.json:
{
// Visit https://aka.ms/tsconfig to read more about this file
"compilerOptions": {
// File Layout
// "rootDir": "./src",
// "outDir": "./dist",
// Environment Settings
// See also https://aka.ms/tsconfig_modules
"module": "nodenext",
"target": "esnext",
"types": [],
// For nodejs:
// "lib": ["esnext"],
// "types": ["node"],
// and npm install -D @types/node
// Other Outputs
"sourceMap": true,
"declaration": true,
"declarationMap": true,
// Stricter Typechecking Options
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
// Style Options
// "noImplicitReturns": true,
// "noImplicitOverride": true,
// "noUnusedLocals": true,
// "noUnusedParameters": true,
// "noFallthroughCasesInSwitch": true,
// "noPropertyAccessFromIndexSignature": true,
// Recommended Options
"strict": true,
"jsx": "react-jsx",
"verbatimModuleSyntax": true,
"isolatedModules": true,
"noUncheckedSideEffectImports": true,
"moduleDetection": "force",
"skipLibCheck": true,
}
}
For more details, see the implementing pull request and discussion issue.
import deferTypeScript 5.9 introduces support for ECMAScript’s deferred module evaluation proposal using the new import defer syntax.
This feature allows you to import a module without immediately executing the module and its dependencies, providing better control over when work and side-effects occur.
The syntax only permits namespace imports:
import defer * as feature from "./some-feature.js";
The key benefit of import defer is that the module is only evaluated when one of its exports is first accessed.
Consider this example:
// ./some-feature.ts
initializationWithSideEffects();
function initializationWithSideEffects() {
// ...
specialConstant = 42;
console.log("Side effects have occurred!");
}
export let specialConstant: number;
When using import defer, the initializationWithSideEffects() function will not be called until you actually access a property of the imported namespace:
import defer * as feature from "./some-feature.js";
// No side effects have occurred yet
// ...
// As soon as `specialConstant` is accessed, the contents of the `feature`
// module are run and side effects have taken place.
console.log(feature.specialConstant); // 42
Because evaluation of the module is deferred until you access a member off of the module, you cannot use named imports or default imports with import defer:
// ❌ Not allowed
import defer { doSomething } from "some-module";
// ❌ Not allowed
import defer defaultExport from "some-module";
// ✅ Only this syntax is supported
import defer * as feature from "some-module";
Note that when you write import defer, the module and its dependencies are fully loaded and ready for execution.
That means that the module will need to exist, and will be loaded from the file system or a network resource.
The key difference between a regular import and import defer is that the execution of statements and declarations is deferred until you access a property of the imported namespace.
This feature is particularly useful for conditionally loading modules with expensive or platform-specific initialization. It can also improve startup performance by deferring module evaluation for app features until they are actually needed.
Note that import defer is not transformed or “downleveled” at all by TypeScript.
It is intended to be used in runtimes that support the feature natively, or by tools such as bundlers that can apply the appropriate transformation.
That means that import defer will only work under the --module modes preserve and esnext.
We’d like to extend our thanks to Nicolò Ribaudo who championed the proposal in TC39 and also provided the implementation for this feature.
--module node20TypeScript provides several node* options for the --module and --moduleResolution settings.
Most recently, --module nodenext has supported the ability to require() ECMAScript modules from CommonJS modules, and correctly rejects import assertions (in favor of the standards-bound import attributes).
TypeScript 5.9 brings a stable option for these settings called node20, intended to model the behavior of Node.js v20.
This option is unlikely to have new behaviors in the future, unlike --module nodenext or --moduleResolution nodenext.
Also unlike nodenext, specifying --module node20 will imply --target es2023 unless otherwise configured.
--module nodenext, on the other hand, implies the floating --target esnext.
For more information, take a look at the implementation here.
Previously, many of the DOM APIs in TypeScript only linked to the MDN documentation for the API. These links were useful, but they didn’t provide a quick summary of what the API does. Thanks to a few changes from Adam Naji, TypeScript now includes summary descriptions for many DOM APIs based on the MDN documentation. You can see more of these changes here and here.
Quick Info (also called “editor tooltips” and “hovers”) can be very useful for peeking at variables to see their types, or at type aliases to see what they actually refer to.
Still, it’s common for people to want to go deeper and get details from whatever’s displayed within the quick info tooltip.
For example, if we hover our mouse over the parameter options in the following example:
export function drawButton(options: Options): void
We’re left with (parameter) options: Options.

Do we really need to jump to the definition of the type Options just to see what members this value has?
Previously, that was actually the case.
To help here, TypeScript 5.9 is now previewing a feature called expandable hovers, or “quick info verbosity”.
If you use an editor like VS Code, you’ll now see a + and - button on the left of these hover tooltips.
Clicking on the + button will expand out types more deeply, while clicking on the - button will collapse to the last view.
This feature is currently in preview, and we are seeking feedback for both TypeScript and our partners on Visual Studio Code. For more details, see the PR for this feature here.
Occasionally, quick info tooltips can become so long that TypeScript will truncate them to make them more readable.
The downside here is that often the most important information will be omitted from the hover tooltip, which can be frustrating.
To help with this, TypeScript 5.9’s language server supports a configurable hover length, which can be configured in VS Code via the js/ts.hover.maximumLength setting.
Additionally, the new default hover length is substantially larger than the previous default. This means that in TypeScript 5.9, you should see more information in your hover tooltips by default. For more details, see the PR for this feature here and the corresponding change to Visual Studio Code here.
When TypeScript replaces type parameters with specific type arguments, it can end up instantiating many of the same intermediate types over and over again. In complex libraries like Zod and tRPC, this could lead to both performance issues and errors reported around excessive type instantiation depth. Thanks to a change from Mateusz Burzyński, TypeScript 5.9 is able to cache many intermediate instantiations when work has already begun on a specific type instantiation. This in turn avoids lots of unnecessary work and allocations.
fileOrDirectoryExistsUsingSourceIn JavaScript, a function expression will typically allocate a new function object, even if the wrapper function is just passing through arguments to another function with no captured variables. In code paths around file existence checks, Vincent Bailly found examples of these pass-through function calls, even though the underlying functions only took single arguments. Given the number of existence checks that could take place in larger projects, he cited a speed-up of around 11%. See more on this change here.
lib.d.ts ChangesTypes generated for the DOM may have an impact on type-checking your codebase.
Additionally, one notable change is that ArrayBuffer has been changed in such a way that it is no longer a supertype of several different TypedArray types.
This also includes subtypes of UInt8Array, such as Buffer from Node.js.
As a result, you’ll see new error messages such as:
error TS2345: Argument of type 'ArrayBufferLike' is not assignable to parameter of type 'BufferSource'.
error TS2322: Type 'ArrayBufferLike' is not assignable to type 'ArrayBuffer'.
error TS2322: Type 'Buffer' is not assignable to type 'Uint8Array<ArrayBufferLike>'.
error TS2322: Type 'Buffer' is not assignable to type 'ArrayBuffer'.
error TS2345: Argument of type 'Buffer' is not assignable to parameter of type 'string | Uint8Array<ArrayBufferLike>'.
If you encounter issues with Buffer, you may first want to check that you are using the latest version of the @types/node package.
This might include running
npm update @types/node --save-dev
Much of the time, the solution is to specify a more specific underlying buffer type instead of using the default ArrayBufferLike (i.e. explicitly writing out Uint8Array<ArrayBuffer> rather than a plain Uint8Array).
In instances where some TypedArray (like Uint8Array) is passed to a function expecting an ArrayBuffer or SharedArrayBuffer, you can also try accessing the buffer property of that TypedArray like in the following example:
let data = new Uint8Array([0, 1, 2, 3, 4]);
- someFunc(data)
+ someFunc(data.buffer)
In an effort to fix “leaks” of type variables during inference, TypeScript 5.9 may introduce changes in types and possibly new errors in some codebases. These are hard to predict, but can often be fixed by adding type arguments to generic functions calls. See more details here.
Now that TypeScript 5.9 is out, you might be wondering what’s in store for the next version: TypeScript 6.0.
As you might have heard, much of our recent focus has been on the native port of TypeScript which will eventually be available as TypeScript 7.0. So what does that mean for TypeScript 6.0?
Our vision for TypeScript 6.0 is to act as a transition point for developers to adjust their codebases for TypeScript 7.0. While TypeScript 6.0 may still ship updates and features, most users should think of it as a readiness check for adopting TypeScript 7.0. This new version is meant to align with TypeScript 7.0, introducing deprecations around certain settings and possibly updating type-checking behavior in small ways. Luckily, we don’t predict most projects will have too much trouble upgrading to TypeScript 6.0, and it will likely be entirely API compatible with TypeScript 5.9.
We’ll have more details coming soon. That includes details on TypeScript 7.0 as well, where you can try it out in Visual Studio Code today and install it right in your project.
Otherwise, we hope that TypeScript 5.9 treats you well, and makes your day-to-day coding a joy.
Happy Hacking!
– Daniel Rosenwasser and the TypeScript Team
The post Announcing TypeScript 5.9 appeared first on TypeScript.
]]>Today we are excited to announce the Release Candidate (RC) of TypeScript 5.9! To get started using the Release Candidate, you can get it through npm with the following command: npm install -D typescript@rc Let’s take a look at what’s new in TypeScript 5.9! Minimal and Updated tsc --init Support for import defer Support for […]
The post Announcing TypeScript 5.9 RC appeared first on TypeScript.
]]>Today we are excited to announce the Release Candidate (RC) of TypeScript 5.9!
To get started using the Release Candidate, you can get it through npm with the following command:
npm install -D typescript@rc
Let’s take a look at what’s new in TypeScript 5.9!
tsc --initimport defer--module node20A few reported fixes have been made since the 5.9 beta, including the restoration of AbortSignal.abort() to the DOM library.
Additionally, we have added a section about Notable Behavioral Changes.
tsc --initFor a while, the TypeScript compiler has supported an --init flag that can create a tsconfig.json within the current directory.
In the last few years, running tsc --init created a very “full” tsconfig.json, filled with commented-out settings and their descriptions.
We designed this with the intent of making options discoverable and easy to toggle.
However, given external feedback (and our own experience), we found it’s common to immediately delete most of the contents of these new tsconfig.json files.
When users want to discover new options, we find they rely on auto-complete from their editor, or navigate to the tsconfig reference on our website (which the generated tsconfig.json links to!).
What each setting does is also documented on that same page, and can be seen via editor hovers/tooltips/quick info.
While surfacing some commented-out settings might be helpful, the generated tsconfig.json was often considered overkill.
We also felt that it was time that tsc --init initialized with a few more prescriptive settings than we already enable.
We looked at some common pain points and papercuts users have when they create a new TypeScript project.
For example, most users write in modules (not global scripts), and --moduleDetection can force TypeScript to treat every implementation file as a module.
Developers also often want to use the latest ECMAScript features directly in their runtime, so --target can typically be set to esnext.
JSX users often find that going back to set --jsx is a needless friction, and its options are slightly confusing.
And often, projects end up loading more declaration files from node_modules/@types than TypeScript actually needs – but specifying an empty types array can help limit this.
In TypeScript 5.9, a plain tsc --init with no other flags will generate the following tsconfig.json:
{
// Visit https://aka.ms/tsconfig to read more about this file
"compilerOptions": {
// File Layout
// "rootDir": "./src",
// "outDir": "./dist",
// Environment Settings
// See also https://aka.ms/tsconfig_modules
"module": "nodenext",
"target": "esnext",
"types": [],
// For nodejs:
// "lib": ["esnext"],
// "types": ["node"],
// and npm install -D @types/node
// Other Outputs
"sourceMap": true,
"declaration": true,
"declarationMap": true,
// Stricter Typechecking Options
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
// Style Options
// "noImplicitReturns": true,
// "noImplicitOverride": true,
// "noUnusedLocals": true,
// "noUnusedParameters": true,
// "noFallthroughCasesInSwitch": true,
// "noPropertyAccessFromIndexSignature": true,
// Recommended Options
"strict": true,
"jsx": "react-jsx",
"verbatimModuleSyntax": true,
"isolatedModules": true,
"noUncheckedSideEffectImports": true,
"moduleDetection": "force",
"skipLibCheck": true,
}
}
For more details, see the implementing pull request and discussion issue.
import deferTypeScript 5.9 introduces support for ECMAScript’s deferred module evaluation proposal using the new import defer syntax.
This feature allows you to import a module without immediately executing the module and its dependencies, providing better control over when work and side-effects occur.
The syntax only permits namespace imports:
import defer * as feature from "./some-feature.js";
The key benefit of import defer is that the module is only evaluated on the first use. Consider this example:
// ./some-feature.ts
initializationWithSideEffects();
function initializationWithSideEffects() {
// ...
specialConstant = 42;
console.log("Side effects have occurred!");
}
export let specialConstant: number;
When using import defer, the initializationWithSideEffects() function will not be called until you actually access a property of the imported namespace:
import defer * as feature from "./some-feature.js";
// No side effects have occurred yet
// ...
// As soon as `specialConstant` is accessed, the contents of the `feature`
// module are run and side effects have taken place.
console.log(feature.specialConstant); // 42
Because evaluation of the module is deferred until you access a member off of the module, you cannot use named imports or default imports with import defer:
// ❌ Not allowed
import defer { doSomething } from "some-module";
// ❌ Not allowed
import defer defaultExport from "some-module";
// ✅ Only this syntax is supported
import defer * as feature from "some-module";
Note that when you write import defer, the module and its dependencies are fully loaded and ready for execution.
That means that the module will need to exist, and will be loaded from the file system or a network resource.
The key difference between a regular import and import defer is that the execution of statements and declarations is deferred until you access a property of the imported namespace.
This feature is particularly useful for conditionally loading modules with expensive or platform-specific initialization. It can also improve startup performance by deferring module evaluation for app features until they are actually needed.
Note that import defer is not transformed or “downleveled” at all by TypeScript.
It is intended to be used in runtimes that support the feature natively, or by tools such as bundlers that can apply the appropriate transformation.
That means that import defer will only work under the --module modes preserve and esnext.
We’d like to extend our thanks to Nicolò Ribaudo who championed the proposal in TC39 and also provided the implementation for this feature.
--module node20TypeScript provides several node* options for the --module and --moduleResolution settings.
Most recently, --module nodenext has supported the ability to require() ECMAScript modules from CommonJS modules, and correctly rejects import assertions (in favor of the standards-bound import attributes).
TypeScript 5.9 brings a stable option for these settings called node20, intended to model the behavior of Node.js v20.
This option is unlikely to have new behaviors in the future, unlike --module nodenext or --moduleResolution nodenext.
Also unlike nodenext, specifying --module node20 will imply --target es2023 unless otherwise configured.
--module nodenext, on the other hand, implies the floating --target esnext.
For more information, take a look at the implementation here.
Previously, many of the DOM APIs in TypeScript only linked to the MDN documentation for the API. These links were useful, but they didn’t provide a quick summary of what the API does. Thanks to a few changes from Adam Naji, TypeScript now includes summary descriptions for many DOM APIs based on the MDN documentation. You can see more of these changes here and here.
Quick Info (also called “editor tooltips” and “hovers”) can be very useful for peeking at variables to see their types, or at type aliases to see what they actually refer to.
Still, it’s common for people to want to go deeper and get details from whatever’s displayed within the quick info tooltip.
For example, if we hover our mouse over the parameter options in the following example:
export function drawButton(options: Options): void
We’re left with (parameter) options: Options.

Do we really need to jump to the definition of the type Options just to see what members this value has?
To help here, TypeScript 5.9 is now previewing a feature called expandable hovers, or “quick info verbosity”.
If you use an editor like VS Code, you’ll now see a + and - button on the left of these hover tooltips.
Clicking on the + button will expand out types more deeply, while clicking on the - will go back to the last view.
This feature is currently in preview, and we are seeking feedback for both TypeScript and our partners on Visual Studio Code. For more details, see the PR for this feature here.
Occasionally, quick info tooltips can become so long that TypeScript will truncate them to make them more readable.
The downside here is that often the most important information will be omitted from the hover tooltip, which can be frustrating.
To help with this, TypeScript 5.9’s language server supports a configurable hover length, which can be configured in VS Code via the js/ts.hover.maximumLength setting.
Additionally, the new default hover length is substantially larger than the previous default. This means that in TypeScript 5.9, you should see more information in your hover tooltips by default. For more details, see the PR for this feature here and the corresponding change to Visual Studio Code here.
When TypeScript replaces type parameters with specific type arguments, it can end up instantiating many of the same intermediate types over and over again. In complex libraries like Zod and tRPC, this could lead to both performance issues and errors reported around excessive type instantiation depth. Thanks to a change from Mateusz Burzyński, TypeScript 5.9 is able to cache many intermediate instantiations when work has already begun on a specific type instantiation. This in turn avoids lots of unnecessary work and allocations.
fileOrDirectoryExistsUsingSourceIn JavaScript, a function expression will typically allocate a new function object, even if the wrapper function is just passing through arguments to another function with no captured variables. In code paths around file existence checks, Vincent Bailly found examples of these pass-through function calls, even though the underlying functions only took single arguments. Given the number of existence checks that could take place in larger projects, he cited a speed-up of around 11%. See more on this change here.
lib.d.ts ChangesTypes generated for the DOM may have an impact on type-checking your codebase.
Additionally, one notable change is that ArrayBuffer has been changed in such a way that it is no longer a supertype of several different TypedArray types.
This also includes subtypes of UInt8Array, such as Buffer from Node.js.
As a result, you’ll see new error messages such as:
error TS2345: Argument of type 'ArrayBufferLike' is not assignable to parameter of type 'BufferSource'.
error TS2322: Type 'ArrayBufferLike' is not assignable to type 'ArrayBuffer'.
error TS2322: Type 'Buffer' is not assignable to type 'Uint8Array<ArrayBufferLike>'.
error TS2322: Type 'Buffer' is not assignable to type 'ArrayBuffer'.
error TS2345: Argument of type 'Buffer' is not assignable to parameter of type 'string | Uint8Array<ArrayBufferLike>'.
If you encounter issues with Buffer, you may first want to check that you are using the latest version of the @types/node package.
This might include running
npm update @types/node --save-dev
Much of the time, the solution is to specify a more specific underyling buffer type instead of using the default ArrayBufferLike (i.e. explicitly writing out Uint8Array<ArrayBuffer> rather than a plain Uint8Array).
In an effort to fix “leaks” of type variables during inference, TypeScript 5.9 may introduces changes in types and possibly new errors in some codebases. These are hard to predict, but can often be fixed by adding type arguments to generic functions calls. See more details here.
As you might have heard, much of our recent focus has been on the native port of TypeScript which will eventually be available as TypeScript 7. You can actually try out the native port today by checking out TypeScript native previews, which are released nightly.
Given that not much has changed since the TypeScript 5.9 beta, we actually plan to release TypeScript 5.9 as a final release candidate within the next week. So we hope you try out the RC today and let us know what you think!
Happy Hacking!
– Daniel Rosenwasser and the TypeScript Team
The post Announcing TypeScript 5.9 RC appeared first on TypeScript.
]]>Today we are excited to announce the availability of TypeScript 5.9 Beta. To get started using the beta, you can get it through npm with the following command: npm install -D typescript@beta Let’s take a look at what’s new in TypeScript 5.9! Minimal and Updated tsc --init Support for import defer Support for --module node20 […]
The post Announcing TypeScript 5.9 Beta appeared first on TypeScript.
]]>Today we are excited to announce the availability of TypeScript 5.9 Beta.
To get started using the beta, you can get it through npm with the following command:
npm install -D typescript@beta
Let’s take a look at what’s new in TypeScript 5.9!
tsc --initimport defer--module node20tsc --initFor a while, the TypeScript compiler has supported an --init flag that can create a tsconfig.json within the current directory.
In the last few years, running tsc --init created a very “full” tsconfig.json, filled with commented-out settings and their descriptions.
We designed this with the intent of making options discoverable and easy to toggle.
However, given external feedback (and our own experience), we found it’s common to immediately delete most of the contents of these new tsconfig.json files.
When users want to discover new options, we find they rely on auto-complete from their editor, or navigate to the tsconfig reference on our website (which the generated tsconfig.json links to!).
What each setting does is also documented on that same page, and can be seen via editor hovers/tooltips/quick info.
While surfacing some commented-out settings might be helpful, the generated tsconfig.json was often considered overkill.
We also felt that it was time that tsc --init initialized with a few more prescriptive settings than we already enable.
We looked at some common pain points and papercuts users have when they create a new TypeScript project.
For example, most users write in modules (not global scripts), and --moduleDetection can force TypeScript to treat every implementation file as a module.
Developers also often want to use the latest ECMAScript features directly in their runtime, so --target can typically be set to esnext.
JSX users often find that going back to set --jsx is a needless friction, and its options are slightly confusing.
And often, projects end up loading more declaration files from node_modules/@types than TypeScript actually needs – but specifying an empty types array can help limit this.
In TypeScript 5.9, a plain tsc --init with no other flags will generate the following tsconfig.json:
{
// Visit https://aka.ms/tsconfig to read more about this file
"compilerOptions": {
// File Layout
// "rootDir": "./src",
// "outDir": "./dist",
// Environment Settings
// See also https://aka.ms/tsconfig_modules
"module": "nodenext",
"target": "esnext",
"types": [],
// For nodejs:
// "lib": ["esnext"],
// "types": ["node"],
// and npm install -D @types/node
// Other Outputs
"sourceMap": true,
"declaration": true,
"declarationMap": true,
// Stricter Typechecking Options
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
// Style Options
// "noImplicitReturns": true,
// "noImplicitOverride": true,
// "noUnusedLocals": true,
// "noUnusedParameters": true,
// "noFallthroughCasesInSwitch": true,
// "noPropertyAccessFromIndexSignature": true,
// Recommended Options
"strict": true,
"jsx": "react-jsx",
"verbatimModuleSyntax": true,
"isolatedModules": true,
"noUncheckedSideEffectImports": true,
"moduleDetection": "force",
"skipLibCheck": true,
}
}
For more details, see the implementing pull request and discussion issue.
import deferTypeScript 5.9 introduces support for ECMAScript’s deferred module evaluation proposal using the new import defer syntax.
This feature allows you to import a module without immediately executing the module and its dependencies, providing better control over when work and side-effects occur.
The syntax only permits namespace imports:
import defer * as feature from "./some-feature.js";
The key benefit of import defer is that the module is only evaluated on the first use. Consider this example:
// ./some-feature.ts
initializationWithSideEffects();
function initializationWithSideEffects() {
// ...
specialConstant = 42;
console.log("Side effects have occurred!");
}
export let specialConstant: number;
When using import defer, the initializationWithSideEffects() function will not be called until you actually access a property of the imported namespace:
import defer * as feature from "./some-feature.js";
// No side effects have occurred yet
// ...
// As soon as `specialConstant` is accessed, the contents of the `feature`
// module are run and side effects have taken place.
console.log(feature.specialConstant); // 42
Because evaluation of the module is deferred until you access a member off of the module, you cannot use named imports or default imports with import defer:
// ❌ Not allowed
import defer { doSomething } from "some-module";
// ❌ Not allowed
import defer defaultExport from "some-module";
// ✅ Only this syntax is supported
import defer * as feature from "some-module";
Note that when you write import defer, the module and its dependencies are fully loaded and ready for execution.
That means that the module will need to exist, and will be loaded from the file system or a network resource.
The key difference between a regular import and import defer is that the execution of statements and declarations is deferred until you access a property of the imported namespace.
This feature is particularly useful for conditionally loading modules with expensive or platform-specific initialization. It can also improve startup performance by deferring module evaluation for app features until they are actually needed.
Note that import defer is not transformed or “downleveled” at all by TypeScript.
It is intended to be used in runtimes that support the feature natively, or by tools such as bundlers that can apply the appropriate transformation.
That means that import defer will only work under the --module modes preserve and esnext.
We’d like to extend our thanks to Nicolò Ribaudo who championed the proposal in TC39 and also provided the implementation for this feature.
--module node20TypeScript provides several node* options for the --module and --moduleResolution settings.
Most recently, --module nodenext has supported the ability to require() ECMAScript modules from CommonJS modules, and correctly rejects import assertions (in favor of the standards-bound import attributes).
TypeScript 5.9 brings a stable option for these settings called node20, intended to model the behavior of Node.js v20.
This option is unlikely to have new behaviors in the future, unlike --module nodenext or --moduleResolution nodenext.
Also unlike nodenext, specifying --module node20 will imply --target es2023 unless otherwise configured.
--module nodenext, on the other hand, implies the floating --target esnext.
For more information, take a look at the implementation here.
Previously, many of the DOM APIs in TypeScript only linked to the MDN documentation for the API. These links were useful, but they didn’t provide a quick summary of what the API does. Thanks to a few changes from Adam Naji, TypeScript now includes summary descriptions for many DOM APIs based on the MDN documentation. You can see more of these changes here and here.
Quick Info (also called “editor tooltips” and “hovers”) can be very useful for peeking at variables to see their types, or at type aliases to see what they actually refer to.
Still, it’s common for people to want to go deeper and get details from whatever’s displayed within the quick info tooltip.
For example, if we hover our mouse over the parameter options in the following example:
export function drawButton(options: Options): void
We’re left with (parameter) options: Options.

Do we really need to jump to the definition of the type Options just to see what members this value has?
To help here, TypeScript 5.9 is now previewing a feature called expandable hovers, or “quick info verbosity”.
If you use an editor like VS Code, you’ll now see a + and - button on the left of these hover tooltips.
Clicking on the + button will expand out types more deeply, while clicking on the - will go back to the last view.
This feature is currently in preview, and we are seeking feedback for both TypeScript and our partners on Visual Studio Code. For more details, see the PR for this feature here.
Occasionally, quick info tooltips can become so long that TypeScript will truncate them to make them more readable.
The downside here is that often the most important information will be omitted from the hover tooltip, which can be frustrating.
To help with this, TypeScript 5.9’s language server supports a configurable hover length, which can be configured in VS Code via the js/ts.hover.maximumLength setting.
Additionally, the new default hover length is substantially larger than the previous default. This means that in TypeScript 5.9, you should see more information in your hover tooltips by default. For more details, see the PR for this feature here and the corresponding change to Visual Studio Code here.
When TypeScript replaces type parameters with specific type arguments, it can end up instantiating many of the same intermediate types over and over again. In complex libraries like Zod and tRPC, this could lead to both performance issues and errors reported around excessive type instantiation depth. Thanks to a change from Mateusz Burzyński, TypeScript 5.9 is able to cache many intermediate instantiations when work has already begun on a specific type instantiation. This in turn avoids lots of unnecessary work and allocations.
fileOrDirectoryExistsUsingSourceIn JavaScript, a function expression will typically allocate a new function object, even if the wrapper function is just passing through arguments to another function with no captured variables. In code paths around file existence checks, Vincent Bailly found examples of these pass-through function calls, even though the underlying functions only took single arguments. Given the number of existence checks that could take place in larger projects, he cited a speed-up of around 11%. See more on this change here.
As you might have heard, much of our recent focus has been on the native port of TypeScript which will eventually be available as TypeScript 7. You can actually try out the native port today by checking out TypeScript native previews, which are released nightly.
However, we are still developing TypeScript 5.9 and addressing issues, and encourage you to try it out and give us feedback. If you need a snapshot of TypeScript that’s newer than the beta, TypeScript also has nightly releases, and you can try out the latest editing experience by installing the JavaScript and TypeScript Nightly extension for Visual Studio Code.
So we hope you try out the beta or a nightly release today and let us know what you think!
Happy Hacking!
– Daniel Rosenwasser and the TypeScript Team
The post Announcing TypeScript 5.9 Beta appeared first on TypeScript.
]]>This past March we unveiled our efforts to port the TypeScript compiler and toolset to native code. This port has achieved a 10x speed-up on most projects – not just by using a natively-compiled language (Go), but also through using shared memory parallelism and concurrency where we can benefit. Since then, we have made several […]
The post Announcing TypeScript Native Previews appeared first on TypeScript.
]]>This past March we unveiled our efforts to port the TypeScript compiler and toolset to native code. This port has achieved a 10x speed-up on most projects – not just by using a natively-compiled language (Go), but also through using shared memory parallelism and concurrency where we can benefit. Since then, we have made several strides towards running on large complex real-world projects.
Today, we are excited to announce broad availability of TypeScript Native Previews. As of today, you will be able to use npm to get a preview of the native TypeScript compiler. Additionally, you’ll be able to use a preview version of our editor functionality for VS Code through the Visual Studio Marketplace.
To get the compiler over npm, you can run the following command in your project:
npm install -D @typescript/native-preview
This package provides an executable called tsgo.
This executable runs similarly to tsc, the existing executable that the typescript package makes available:
npx tsgo --project ./src/tsconfig.json
Eventually we will rename tsgo to tsc and move it to the typescript package.
For now, it lives separately for easier testing.
The new executable is still a work in progress, but is suitable to type-check and build many real-world projects.
But we know that a command-line compiler is only half the story. We’ve heard teams are eager to see what the new editing experience is like too, and so you can now install the new “TypeScript (Native Preview)” extension in Visual Studio Code. You can easily install it off of the VS Code Extension Marketplace.
Because the extension is still in early stages of development, it defers to the built-in TypeScript extension in VS Code. For that reason, the extension will need to be enabled even after installation. You can do this by opening VS Code’s command palette and running the command “TypeScript Native Preview: Enable (Experimental)”.

Alternatively, you can toggle this in your settings UI by configuring “TypeScript > Experimental: Use Tsgo”

or by adding the following line to your JSON settings:
"typescript.experimental.useTsgo": true,
These previews will eventually become TypeScript 7 and will be published nightly so that you can easily try the latest developments on the TypeScript native port effort. If you use the VS Code extension, you should get automatic updates by default. If for whatever reason you find any sort of disruption, we encourage you to file an issue and temporarily disable the new language service with the command “TypeScript Native Preview: Disable”:

or by configuring any of the settings mentioned above.
Keep in mind, these native previews are missing lots of functionality that stable versions of TypeScript have today.
That includes command-line functionality like --build (though individual projects can still be built with tsgo), --declaration emit, and certain downlevel emit targets.
Similarly, editor functionality like auto-imports, find-all-references, and rename are still pending implementation.
But we encourage developers to check back frequently, as we’ll be hard at work on these features!
Since our initial announcement, we have made some notable strides in type-checking support, testability, editor support, and APIs. We would also love to give a brief update of what we’ve accomplished, plus what’s on the horizon.
Note that while the native preview will eventually be called TypeScript 7, we’ve casually been referring to it as “Project Corsa” in the meantime. We’ve also been more explicit in referring to the codebase that makes up TypeScript 5.8 as our current JS-based codebase, or “Strada”. So in our updates, you’ll see us differentiate the native and stable versions of TypeScript as “Corsa” (TS7) and “Strada” (TS 5.8).
The majority of the type-checker has been ported at this time.
That is to say, most projects should see the same errors apart from those affected by some intentional changes (e.g. this change to the ordering of types) and some stale definitions in lib.d.ts.
If you see any divergences and differences, we encourage you to file an issue to let us know.
It is worth calling out support for two major type-checking features that have been added since our initial announcement: JSX and JavaScript+JSDoc.
When developers first got access to the TypeScript native port, we had to temper expectations. While type-checking was pretty far along, some constructs were still not fully checked yet. For many developers, the most notable omission was JSX. While Corsa was able to parse JSX, it would mostly just pass over JSX expressions when type-checking and note that JSX was not-yet supported.
Since then, we’ve actually added type-checking support for JSX and we can get a better sense of how fast a real JSX project can be built.
As an example codebase, we looked at the codebase for Sentry.
If you run TypeScript 5.8 from the repository root with --extendedDiagnostics --noEmit, you’ll get something like the following:
$ tsc -p . --noEmit --extendedDiagnostics
Files: 9306
Lines of Library: 43159
Lines of Definitions: 352182
Lines of TypeScript: 1113969
Lines of JavaScript: 1106
Lines of JSON: 304
Lines of Other: 0
Identifiers: 1956007
Symbols: 3563371
Types: 999619
Instantiations: 3675199
Memory used: 3356832K
Assignability cache size: 944737
Identity cache size: 43226
Subtype cache size: 110171
Strict subtype cache size: 430338
I/O Read time: 1.40s
Parse time: 3.48s
ResolveModule time: 1.88s
ResolveTypeReference time: 0.02s
ResolveLibrary time: 0.01s
Program time: 7.78s
Bind time: 1.77s
Check time: 63.26s
printTime time: 0.00s
Emit time: 0.00s
Total time: 72.81s
That’s over a minute to type-check this codebase! Let’s see how the native port fares with some minimal changes.
$ tsgo -p . --noEmit --extendedDiagnostics
...
Files: 9292
Lines: 1508361
Identifiers: 1954236
Symbols: 5011565
Types: 1689528
Instantiations: 6524885
Memory used: 3892267K
Memory allocs: 61043466
Parse time: 0.712s
Bind time: 0.133s
Check time: 5.882s
Emit time: 0.012s
Total time: 6.761s
There are some discrepancies in results, but Corsa brings build times down from over a minute to just under 7 seconds on the same machine.
Your results may vary, but in general we’ve seen consistent speed-ups of over 10x on this specific example.
You can try introducing an error in existing JSX code and tsgo will catch it.
You can see more over at our PR to port JSX type-checking, plus some follow-on support for tslib and JSX factory imports.
TypeScript supports parsing and type-checking JavaScript files.
Because valid JavaScript/ECMAScript doesn’t support type-specific syntax like annotations or interface and type declarations, TypeScript looks at JSDoc comments in JS source code for type analysis.
The native previews of TypeScript now also support type-checking JS files. In developing JS type-checking for Corsa, we revisited our early decisions in our implementation. JavaScript support was built up in a very organic way and, in turn, analyzed very specific patterns that may no longer be (or may never have been) in widespread use. In order to simplify the new codebase, JavaScript support has been rewritten rather than ported. As a result, there may be some constructs that may need to be rewritten, or to use a more idiomatic/modern JS style.
If this causes difficulties for your project, we are open to feedback on the issue tracker.
When we released the Corsa codebase, it included a very rudimentary LSP-based language server. While most tangible development has been on the compiler itself, we have been iterating on multiple fronts to port our editor functionality in this new system. Because the Strada codebase communicates with editors via the TSServer format that predates LSP, we are not aiming to do a perfect 1:1 port between the codebases. This means that porting code often requires more manual porting and has required a bit more up-front thought in how we generate type definitions that conform to LSP. Gathering errors/diagnostics, go-to-definition, and hover work in very early stages.
Most recently, we have hit another milestone: we have enabled completions! While auto-imports and other features around completions are not fully ported, this may be enough for many teams in large codebases. Going forward, our priorities are in porting over our existing language server test suite, along with enabling find-all-references, rename, and signature help.
A big challenge as part of this port will be continuity with API consumers of TypeScript. We have the initial foundation of an API layer that can be leveraged over standard I/O. This work means that API consumers can communicate with a TypeScript process through IPC regardless of the consuming language. Since we know that many API consumers will be writing TypeScript and JavaScript code, we also have JavaScript-based clients for interacting with the API.
Because so much TypeScript API usage today is synchronous, we wanted to make it possible to communicate with this process in a synchronous way. Node.js unfortunately doesn’t provide an easy way to communicate synchronously with a child process, so we developed a native Node.js module in Rust (which should make lots of people happy) called libsyncrpc.
We are still in the early days of API design here, but we are open to thoughts and feedback on the matter. More details about the current API server are available here.
As we’ve mentioned, the Corsa compiler and language service may still have some differences from Strada.
There are some differences that you may hit early on in trying out tsgo and the Native Preview VS Code extension.
Some of those come from eventual TypeScript 6.0 deprecations, like node/node10 resolution (in favor of node16, nodenext, and bundler).
If you use --moduleResolution node or --module commonjs, you may see some errors like:
Cannot find module 'blah' or its corresponding type declarations.
Module '"module"' has no exported member 'Thing'.
You will get consistent errors if you switch your tsconfig.json settings to use
{
"compilerOptions": {
// ...
"module": "preserve",
"moduleResolution": "bundler",
}
}
or
{
"compilerOptions": {
// ...
"module": "nodenext"
}
}
These can be manually fixed depending on your configuration, though often you can remove the imports and leverage auto-imports to do “the right thing”.
Beyond deprecations, downlevel emit to older targets is limited, and JSX emit only works as far as preserving what you wrote.
Declaration emit is currently not supported either.
--build mode and language service functionality around project references is still not available, though project dependencies can be built through tsc, and the native preview language service can often leverage generated .d.ts files.
By later this year, we will aim to have a more complete version of our compiler with major features like --build, along with most language service features for editors.
But we don’t expect you to wait that long! As TypeScript Native Previews are published nightly, we’ll aim to provide periodic updates on major notable developments. So give the native previews a shot!
Happy Hacking!
– Daniel Rosenwasser and the TypeScript Team
The post Announcing TypeScript Native Previews appeared first on TypeScript.
]]>Today I’m excited to announce the next steps we’re taking to radically improve TypeScript performance. The core value proposition of TypeScript is an excellent developer experience. As your codebase grows, so does the value of TypeScript itself, but in many cases TypeScript has not been able to scale up to the very largest codebases. Developers […]
The post A 10x Faster TypeScript appeared first on TypeScript.
]]>Today I’m excited to announce the next steps we’re taking to radically improve TypeScript performance.
The core value proposition of TypeScript is an excellent developer experience. As your codebase grows, so does the value of TypeScript itself, but in many cases TypeScript has not been able to scale up to the very largest codebases. Developers working in large projects can experience long load and check times, and have to choose between reasonable editor startup time or getting a complete view of their source code. We know developers love when they can rename variables with confidence, find all references to a particular function, easily navigate their codebase, and do all of those things without delay. New experiences powered by AI benefit from large windows of semantic information that need to be available with tighter latency constraints. We also want fast command-line builds to validate that your entire codebase is in good shape.
To meet those goals, we’ve begun work on a native port of the TypeScript compiler and tools.
The native implementation will drastically improve editor startup, reduce most build times by 10x, and substantially reduce memory usage.
By porting the current codebase, we expect to be able to preview a native implementation of tsc capable of command-line typechecking by mid-2025, with a feature-complete solution for project builds and a language service by the end of the year.
You can build and run the Go code from our new working repo, which is offered under the same license as the existing TypeScript codebase.
Check the README for instructions on how to build and run tsc and the language server, and to see a summary of what’s implemented so far.
We’ll be posting regular updates as new functionality becomes available for testing.
Our native implementation is already capable of loading many popular TypeScript projects, including the TypeScript compiler itself.
Here are times to run tsc on some popular codebases on GitHub of varying sizes:
| Codebase | Size (LOC) | Current | Native | Speedup |
|---|---|---|---|---|
| VS Code | 1,505,000 | 77.8s | 7.5s | 10.4x |
| Playwright | 356,000 | 11.1s | 1.1s | 10.1x |
| TypeORM | 270,000 | 17.5s | 1.3s | 13.5x |
| date-fns | 104,000 | 6.5s | 0.7s | 9.5x |
| tRPC (server + client) | 18,000 | 5.5s | 0.6s | 9.1x |
| rxjs (observable) | 2,100 | 1.1s | 0.1s | 11.0x |
While we’re not yet feature-complete, these numbers are representative of the order of magnitude performance improvement you’ll see checking most codebases.
We’re incredibly excited about the opportunities that this massive speed boost creates. Features that once seemed out of reach are now within grasp. This native port will be able to provide instant, comprehensive error listings across an entire project, support more advanced refactorings, and enable deeper insights that were previously too expensive to compute. This new foundation goes beyond today’s developer experience and will enable the next generation of AI tools to enhance development, powering new tools that will learn, adapt, and improve the coding experience.
Most developer time is spent in editors, and it’s where performance is most important. We want editors to load large projects quickly, and respond quickly in all situations. Modern editors like Visual Studio and Visual Studio Code have excellent performance as long as the underlying language services are also fast. With our native implementation, we’ll be able to provide incredibly fast editor experiences.
Again using the Visual Studio Code codebase as a benchmark, the current time to load the entire project in the editor on a fast computer is about 9.6 seconds. This drops down to about 1.2 seconds with the native language service, an 8x improvement in project load time in editor scenarios. What this translates to is a faster working experience from the time you open your editor to your first keystroke in any TypeScript codebase. We expect all projects to see this level of improvement in load time.
Overall memory usage also appears to be roughly half of the current implementation, though we haven’t actively investigated optimizing this yet and expect to realize further improvements. Editor responsiveness for all language service operations (including completion lists, quick info, go to definition, and find all references) will also see significant speed gains. We’ll also be moving to the Language Server Protocol (LSP), a longstanding infrastructural work item to better align our implementation with other languages.
Our most recent TypeScript release was TypeScript 5.8, with TypeScript 5.9 coming soon. The JS-based codebase will continue development into the 6.x series, and TypeScript 6.0 will introduce some deprecations and breaking changes to align with the upcoming native codebase.
When the native codebase has reached sufficient parity with the current TypeScript, we’ll be releasing it as TypeScript 7.0. This is still in development and we’ll be announcing stability and feature milestones as they occur.
For the sake of clarity, we’ll refer to them simply as TypeScript 6 (JS) and TypeScript 7 (native), since this will be the nomenclature for the foreseeable future. You may also see us refer to “Strada” (the original TypeScript codename) and “Corsa” (the codename for this effort) in internal discussions or code comments.
While some projects may be able to switch to TypeScript 7 upon release, others may depend on certain API features, legacy configurations, or other constraints that necessitate using TypeScript 6. Recognizing TypeScript’s critical role in the JS development ecosystem, we’ll still be maintaining the JS codebase in the 6.x line until TypeScript 7+ reaches sufficient maturity and adoption.
Our long-term goal is to keep these versions as closely aligned as possible so that you can upgrade to TypeScript 7 as soon as it meets your requirements, or fall back to TypeScript 6 if necessary.
In the coming months we’ll be sharing more about this exciting effort, including deeper looks into performance, a new compiler API, LSP, and more. We’ve written up some FAQs on the GitHub repo to address some questions we expect you might have. We also invite you to join us for an AMA at the TypeScript Community Discord at 10 AM PDT | 5 PM UTC on March 13th.
A 10x performance improvement represents a massive leap in the TypeScript and JavaScript development experience, so we hope you are as enthusiastic as we are for this effort!
The post A 10x Faster TypeScript appeared first on TypeScript.
]]>Today we’re excited to announce the release of TypeScript 5.8! If you’re not familiar with TypeScript, it’s a language that builds on top of JavaScript by adding syntax for types. Writing types in our code allows us to explain intent and have other tools check our code to catch mistakes like typos, issues with null […]
The post Announcing TypeScript 5.8 appeared first on TypeScript.
]]>Today we’re excited to announce the release of TypeScript 5.8!
If you’re not familiar with TypeScript, it’s a language that builds on top of JavaScript by adding syntax for types.
Writing types in our code allows us to explain intent and have other tools check our code to catch mistakes like typos, issues with null and undefined, and more.
Types also power TypeScript’s editor tooling like the auto-completion, code navigation, and refactorings that you might see in editors like Visual Studio and VS Code.
In fact, TypeScript and its ecosystem powers the JavaScript experience in both of those editors as well!
To get started using TypeScript, you can install it through npm with the following command:
npm install -D typescript
Let’s take a look at what’s new in TypeScript 5.8!
Since our beta release, we have had to pull back some work on how functions with conditional return types are checked. Based on some of the limitations and changes we wanted to make, we decided to iterate on the feature with the goal of shipping it in TypeScript 5.9. However, as part of this work, we added more granular checks for branches within return expressions. This enhancement was not documented in the beta post, but will remain in TypeScript 5.8.
No new major changes have been added since the release candidate.
Consider some code like the following:
declare const untypedCache: Map<any, any>;
function getUrlObject(urlString: string): URL {
return untypedCache.has(urlString) ?
untypedCache.get(urlString) :
urlString;
}
The intent of this code is to retrieve a URL object from a cache if it exists, or to create a new URL object if it doesn’t. However, there’s a bug: we forgot to actually construct a new URL object with the input. Unfortunately, TypeScript generally didn’t catch this sort of bug.
When TypeScript checks conditional expressions like cond ? trueBranch : falseBranch, its type is treated as a union of the types of the two branches.
In other words, it gets the type of trueBranch and falseBranch, and combines them into a union type.
In this case, the type of untypedCache.get(urlString) is any, and the type of urlString is string.
This is where things go wrong because any is so infectious in how it interacts with other types.
The union any | string is simplified to any, so by the time TypeScript starts checking whether the expression in our return statement is compatible with the expected return type of URL, the type system has lost any information that would have caught the bug in this code.
In TypeScript 5.8, the type system special-cases conditional expressions directly inside return statements.
Each branch of the conditional is checked against the declared return type of the containing functions (if one exists), so the type system can catch the bug in the example above.
declare const untypedCache: Map<any, any>;
function getUrlObject(urlString: string): URL {
return untypedCache.has(urlString) ?
untypedCache.get(urlString) :
urlString;
// ~~~~~~~~~
// error! Type 'string' is not assignable to type 'URL'.
}
This change was made within this pull request, as part of a broader set of future improvements for TypeScript.
require() of ECMAScript Modules in --module nodenextFor years, Node.js supported ECMAScript modules (ESM) alongside CommonJS modules. Unfortunately, the interoperability between the two had some challenges.
import CommonJS filesrequire() ESM filesIn other words, consuming CommonJS files from ESM files was possible, but not the other way around. This introduced many challenges for library authors who wanted to provide ESM support. These library authors would either have to break compatibility with CommonJS users, “dual-publish” their libraries (providing separate entry-points for ESM and CommonJS), or just stay on CommonJS indefinitely. While dual-publishing might sound like a good middle-ground, it is a complex and error-prone process that also roughly doubles the amount of code within a package.
Node.js 22 relaxes some of these restrictions and permits require("esm") calls from CommonJS modules to ECMAScript modules.
Node.js still does not permit require() on ESM files that contain a top-level await, but most other ESM files are now consumable from CommonJS files.
This presents a major opportunity for library authors to provide ESM support without having to dual-publish their libraries.
TypeScript 5.8 supports this behavior under the --module nodenext flag.
When --module nodenext is enabled, TypeScript will avoid issuing errors on these require() calls to ESM files.
Because this feature may be back-ported to older versions of Node.js, there is currently no stable --module nodeXXXX option that enables this behavior;
however, we predict future versions of TypeScript may be able to stabilize the feature under node20.
In the meantime, we encourage users of Node.js 22 and newer to use --module nodenext, while library authors and users of older Node.js versions should remain on --module node16 (or make the minor update to --module node18).
For more information, see our support for require(“esm”) here.
--module node18TypeScript 5.8 introduces a stable --module node18 flag.
For users who are fixed on using Node.js 18, this flag provides a stable point of reference that does not incorporate certain behaviors that are in --module nodenext.
Specifically:
require() of ECMAScript modules is disallowed under node18, but allowed under nodenextnode18, but are disallowed under nodenextSee more at both the --module node18 pull request and changes made to --module nodenext.
--erasableSyntaxOnly OptionRecently, Node.js 23.6 unflagged experimental support for running TypeScript files directly;
however, only certain constructs are supported under this mode.
Node.js has unflagged a mode called --experimental-strip-types which requires that any TypeScript-specific syntax cannot have runtime semantics.
Phrased differently, it must be possible to easily erase or “strip out” any TypeScript-specific syntax from a file, leaving behind a valid JavaScript file.
That means constructs like the following are not supported:
enum declarationsnamespaces and modules with runtime codeimport = aliasesHere are some examples of what does not work:
// ❌ error: A namespace with runtime code.
namespace container {
foo.method();
export type Bar = string;
}
// ❌ error: An `import =` alias
import Bar = container.Bar;
class Point {
// ❌ error: Parameter properties
constructor(public x: number, public y: number) { }
}
// ❌ error: An enum declaration.
enum Direction {
Up,
Down,
Left,
Right,
}
Similar tools like ts-blank-space or Amaro (the underlying library for type-stripping in Node.js) have the same limitations. These tools will provide helpful error messages if they encounter code that doesn’t meet these requirements, but you still won’t find out your code doesn’t work until you actually try to run it.
That’s why TypeScript 5.8 introduces the --erasableSyntaxOnly flag.
When this flag is enabled, TypeScript will error on most TypeScript-specific constructs that have runtime behavior.
class C {
constructor(public x: number) { }
// ~~~~~~~~~~~~~~~~
// error! This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
}
}
Typically, you will want to combine this flag with the --verbatimModuleSyntax, which ensures that a module contains the appropriate import syntax, and that import elision does not take place.
For more information, see the implementation here.
--libReplacement FlagIn TypeScript 4.5, we introduced the possibility of substituting the default lib files with custom ones.
This was based on the possibility of resolving a library file from packages named @typescript/lib-*.
For example, you could lock your dom libraries onto a specific version of the @types/web package with the following package.json:
{
"devDependencies": {
"@typescript/lib-dom": "npm:@types/[email protected]"
}
}
When installed, a package called @typescript/lib-dom should exist, and TypeScript will currently always look it up when dom is implied by your settings.
This is a powerful feature, but it also incurs a bit of extra work.
Even if you’re not using this feature, TypeScript always performs this lookup, and has to watch for changes in node_modules in case a lib-replacement package begins to exist.
TypeScript 5.8 introduces the --libReplacement flag, which allows you to disable this behavior.
If you’re not using --libReplacement, you can now disable it with --libReplacement false.
In the future --libReplacement false may become the default, so if you currently rely on the behavior you should consider explicitly enabling it with --libReplacement true.
For more information, see the change here.
In an effort to make computed properties have more predictable emit in declaration files, TypeScript 5.8 will consistently preserve entity names (bareVariables and dotted.names.that.look.like.this) in computed property names in classes.
For example, consider the following code:
export let propName = "theAnswer";
export class MyClass {
[propName] = 42;
// ~~~~~~~~~~
// error!
// A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type.
}
Previous versions of TypeScript would issue an error when generating a declaration file for this module, and a best-effort declaration file would generate an index signature.
export declare let propName: string;
export declare class MyClass {
[x: string]: number;
}
In TypeScript 5.8, the example code is now allowed, and the emitted declaration file will match what you wrote:
export declare let propName: string;
export declare class MyClass {
[propName]: number;
}
Note that this does not create statically-named properties on the class.
You’ll still end up with what is effectively an index signature like [x: string]: number, so for that use case, you’d need to use unique symbols or literal types.
Note that writing this code was and currently is an error under the --isolatedDeclarations flag;
but we expect that thanks to this change, computed property names will generally be permitted in declaration emit.
Note that it’s possible (though unlikely) that a file compiled in TypeScript 5.8 may generate a declaration file that is not backward compatible in TypeScript 5.7 or earlier.
For more information, see the implementing PR.
TypeScript 5.8 introduces a number of optimizations that can both improve the time to build up a program, and also to update a program based on a file change in either --watch mode or editor scenarios.
First, TypeScript now avoids array allocations that would be involved while normalizing paths. Typically, path normalization would involve segmenting each portion of a path into an array of strings, normalizing the resulting path based on relative segments, and then joining them back together using a canonical separator. For projects with many files, this can be a significant and repetitive amount of work. TypeScript now avoids allocating an array, and operates more directly on indexes of the original path.
Additionally, when edits are made that don’t change the fundamental structure of a project, TypeScript now avoids re-validating the options provided to it (e.g. the contents of a tsconfig.json).
This means, for example, that a simple edit might not require checking that the output paths of a project don’t conflict with the input paths.
Instead, the results of the last check can be used.
This should make edits in large projects feel more responsive.
This section highlights a set of noteworthy changes that should be acknowledged and understood as part of any upgrade. Sometimes it will highlight deprecations, removals, and new restrictions. It can also contain bug fixes that are functionally improvements, but which can also affect an existing build by introducing new errors.
lib.d.tsTypes generated for the DOM may have an impact on type-checking your codebase.
For more information, see linked issues related to DOM and lib.d.ts updates for this version of TypeScript.
--module nodenextImport assertions were a proposed addition to ECMAScript to ensure certain properties of an import (e.g. “this module is JSON, and is not intended to be executable JavaScript code”).
They were reinvented as a proposal called import attributes.
As part of the transition, they swapped from using the assert keyword to using the with keyword.
// An import assertion ❌ - not future-compatible with most runtimes.
import data from "./data.json" assert { type: "json" };
// An import attribute ✅ - the preferred way to import a JSON file.
import data from "./data.json" with { type: "json" };
Node.js 22 no longer accepts import assertions using the assert syntax.
In turn when --module nodenext is enabled in TypeScript 5.8, TypeScript will issue an error if it encounters an import assertion.
import data from "./data.json" assert { type: "json" };
// ~~~~~~
// error! Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'
For more information, see the change here
The next version of TypeScript will be TypeScript 5.9, and we’ll have more details through an upcoming iteration plan on our issue tracker.
That will have precise target dates and more details on upcoming features that we plan to work on.
In the meantime, you can try out early versions of TypeScript 5.9 today by installing our nightly builds from npm with npm install typescript@next, or by using the VS Code TypeScript Nightly extension.
Until then, TypeScript 5.8 is here and ready to use, and we’re excited for you to install it today! We hope that this release makes your day-to-day coding a joy.
Happy Hacking!
– Daniel Rosenwasser and the TypeScript Team
The post Announcing TypeScript 5.8 appeared first on TypeScript.
]]>Today we are excited to announce the Release Candidate (RC) of TypeScript 5.8! To get started using the Release Candidate, you can get it through npm with the following command: npm install -D typescript@rc Let’s take a look at what’s new in TypeScript 5.8! What’s New Since the Beta? Since our beta release, we have […]
The post Announcing TypeScript 5.8 RC appeared first on TypeScript.
]]>Today we are excited to announce the Release Candidate (RC) of TypeScript 5.8!
To get started using the Release Candidate, you can get it through npm with the following command:
npm install -D typescript@rc
Let’s take a look at what’s new in TypeScript 5.8!
Since our beta release, we have had to pull back some work on how functions with conditional return types are checked. Based on some of the limitations and changes we wanted to make, we decided to iterate on the feature with the goal of shipping it in TypeScript 5.9. However, as part of this work, we added more granular checks for branches within return expressions. This enhancement was not documented in the beta post, but will remain in TypeScript 5.8.
Consider some code like the following:
declare const untypedCache: Map<any, any>;
function getUrlObject(urlString: string): URL {
return untypedCache.has(urlString) ?
untypedCache.get(urlString) :
urlString;
}
The intent of this code is to retrieve a URL object from a cache if it exists, or to create a new URL object if it doesn’t. However, there’s a bug: we forgot to actually construct a new URL object with the input. Unfortunately, TypeScript generally didn’t catch this sort of bug.
When TypeScript checks conditional expressions like cond ? trueBranch : falseBranch, its type is treated as a union of the types of the two branches.
In other words, it gets the type of trueBranch and falseBranch, and combines them into a union type.
In this case, the type of untypedCache.get(urlString) is any, and the type of urlString is string.
This is where things go wrong because any is so infectious in how it interacts with other types.
The union any | string is simplified to any, so by the time TypeScript starts checking whether the expression in our return statement is compatible with the expected return type of URL, the type system has lost any information that would have caught the bug in this code.
In TypeScript 5.8, the type system special-cases conditional expressions directly inside return statements.
Each branch of the conditional is checked against the declared return type of the containing functions (if one exists), so the type system can catch the bug in the example above.
declare const untypedCache: Map<any, any>;
function getUrlObject(urlString: string): URL {
return untypedCache.has(urlString) ?
untypedCache.get(urlString) :
urlString;
// ~~~~~~~~~
// error! Type 'string' is not assignable to type 'URL'.
}
This change was made within this pull request, as part of a broader set of future improvements for TypeScript.
require() of ECMAScript Modules in --module nodenextFor years, Node.js supported ECMAScript modules (ESM) alongside CommonJS modules. Unfortunately, the interoperability between the two had some challenges.
import CommonJS filesrequire() ESM filesIn other words, consuming CommonJS files from ESM files was possible, but not the other way around. This introduced many challenges for library authors who wanted to provide ESM support. These library authors would either have to break compatibility with CommonJS users, "dual-publish" their libraries (providing separate entry-points for ESM and CommonJS), or just stay on CommonJS indefinitely. While dual-publishing might sound like a good middle-ground, it is a complex and error-prone process that also roughly doubles the amount of code within a package.
Node.js 22 relaxes some of these restrictions and permits require("esm") calls from CommonJS modules to ECMAScript modules.
Node.js still does not permit require() on ESM files that contain a top-level await, but most other ESM files are now consumable from CommonJS files.
This presents a major opportunity for library authors to provide ESM support without having to dual-publish their libraries.
TypeScript 5.8 supports this behavior under the --module nodenext flag.
When --module nodenext is enabled, TypeScript will avoid issuing errors on these require() calls to ESM files.
Because this feature may be back-ported to older versions of Node.js, there is currently no stable --module nodeXXXX option that enables this behavior;
however, we predict future versions of TypeScript may be able to stabilize the feature under node20.
In the meantime, we encourage users of Node.js 22 and newer to use --module nodenext, while library authors and users of older Node.js versions should remain on --module node16 (or make the minor update to --module node18).
For more information, see our support for require("esm") here.
--module node18TypeScript 5.8 introduces a stable --module node18 flag.
For users who are fixed on using Node.js 18, this flag provides a stable point of reference that does not incorporate certain behaviors that are in --module nodenext.
Specifically:
require() of ECMAScript modules is disallowed under node18, but allowed under nodenextnode18, but are disallowed under nodenextSee more at both the --module node18 pull request and changes made to --module nodenext.
--erasableSyntaxOnly OptionRecently, Node.js 23.6 unflagged experimental support for running TypeScript files directly;
however, only certain constructs are supported under this mode.
Node.js has unflagged a mode called --experimental-strip-types which requires that any TypeScript-specific syntax cannot have runtime semantics.
Phrased differently, it must be possible to easily erase or "strip out" any TypeScript-specific syntax from a file, leaving behind a valid JavaScript file.
That means constructs like the following are not supported:
enum declarationsnamespaces and modules with runtime codeimport = aliasesHere are some examples of what does not work:
// ❌ error: A namespace with runtime code.
namespace container {
foo.method();
export type Bar = string;
}
// ❌ error: An `import =` alias
import Bar = container.Bar;
class Point {
// ❌ error: Parameter properties
constructor(public x: number, public y: number) { }
}
// ❌ error: An enum declaration.
enum Direction {
Up,
Down,
Left,
Right,
}
Similar tools like ts-blank-space or Amaro (the underlying library for type-stripping in Node.js) have the same limitations. These tools will provide helpful error messages if they encounter code that doesn’t meet these requirements, but you still won’t find out your code doesn’t work until you actually try to run it.
That’s why TypeScript 5.8 introduces the --erasableSyntaxOnly flag.
When this flag is enabled, TypeScript will error on most TypeScript-specific constructs that have runtime behavior.
class C {
constructor(public x: number) { }
// ~~~~~~~~~~~~~~~~
// error! This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
}
}
Typically, you will want to combine this flag with the --verbatimModuleSyntax, which ensures that a module contains the appropriate import syntax, and that import elision does not take place.
For more information, see the implementation here.
--libReplacement FlagIn TypeScript 4.5, we introduced the possibility of substituting the default lib files with custom ones.
This was based on the possibility of resolving a library file from packages named @typescript/lib-*.
For example, you could lock your dom libraries onto a specific version of the @types/web package with the following package.json:
{
"devDependencies": {
"@typescript/lib-dom": "npm:@types/[email protected]"
}
}
When installed, a package called @typescript/lib-dom should exist, and TypeScript will currently always look it up when dom is implied by your settings.
This is a powerful feature, but it also incurs a bit of extra work.
Even if you’re not using this feature, TypeScript always performs this lookup, and has to watch for changes in node_modules in case a lib-replacement package begins to exist.
TypeScript 5.8 introduces the --libReplacement flag, which allows you to disable this behavior.
If you’re not using --libReplacement, you can now disable it with --libReplacement false.
In the future --libReplacement false may become the default, so if you currently rely on the behavior you should consider explicitly enabling it with --libReplacement true.
For more information, see the change here.
In an effort to make computed properties have more predictable emit in declaration files, TypeScript 5.8 will consistently preserve entity names (bareVariables and dotted.names.that.look.like.this) in computed property names in classes.
For example, consider the following code:
export let propName = "theAnswer";
export class MyClass {
[propName] = 42;
// ~~~~~~~~~~
// error!
// A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type.
}
Previous versions of TypeScript would issue an error when generating a declaration file for this module, and a best-effort declaration file would generate an index signature.
export declare let propName: string;
export declare class MyClass {
[x: string]: number;
}
In TypeScript 5.8, the example code is now allowed, and the emitted declaration file will match what you wrote:
export declare let propName: string;
export declare class MyClass {
[propName]: number;
}
Note that this does not create statically-named properties on the class.
You’ll still end up with what is effectively an index signature like [x: string]: number, so for that use case, you’d need to use unique symbols or literal types.
Note that writing this code was and currently is an error under the --isolatedDeclarations flag;
but we expect that thanks to this change, computed property names will generally be permitted in declaration emit.
Note that it’s possible (though unlikely) that a file compiled in TypeScript 5.8 may generate a declaration file that is not backward compatible in TypeScript 5.7 or earlier.
For more information, see the implementing PR.
TypeScript 5.8 introduces a number of optimizations that can both improve the time to build up a program, and also to update a program based on a file change in either --watch mode or editor scenarios.
First, TypeScript now avoids array allocations that would be involved while normalizing paths. Typically, path normalization would involve segmenting each portion of a path into an array of strings, normalizing the resulting path based on relative segments, and then joining them back together using a canonical separator. For projects with many files, this can be a significant and repetitive amount of work. TypeScript now avoids allocating an array, and operates more directly on indexes of the original path.
Additionally, when edits are made that don’t change the fundamental structure of a project, TypeScript now avoids re-validating the options provided to it (e.g. the contents of a tsconfig.json).
This means, for example, that a simple edit might not require checking that the output paths of a project don’t conflict with the input paths.
Instead, the results of the last check can be used.
This should make edits in large projects feel more responsive.
This section highlights a set of noteworthy changes that should be acknowledged and understood as part of any upgrade. Sometimes it will highlight deprecations, removals, and new restrictions. It can also contain bug fixes that are functionally improvements, but which can also affect an existing build by introducing new errors.
lib.d.tsTypes generated for the DOM may have an impact on type-checking your codebase.
For more information, see linked issues related to DOM and lib.d.ts updates for this version of TypeScript.
--module nodenextImport assertions were a proposed addition to ECMAScript to ensure certain properties of an import (e.g. "this module is JSON, and is not intended to be executable JavaScript code").
They were reinvented as a proposal called import attributes.
As part of the transition, they swapped from using the assert keyword to using the with keyword.
// An import assertion ❌ - not future-compatible with most runtimes.
import data from "./data.json" assert { type: "json" };
// An import attribute ✅ - the preferred way to import a JSON file.
import data from "./data.json" with { type: "json" };
Node.js 22 no longer accepts import assertions using the assert syntax.
In turn when --module nodenext is enabled in TypeScript 5.8, TypeScript will issue an error if it encounters an import assertion.
import data from "./data.json" assert { type: "json" };
// ~~~~~~
// error! Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'
For more information, see the change here
At this point, we anticipate very few changes to TypeScript 5.8 apart from critical bug fixes to the compiler and minor bug fixes to the language service. In the next few weeks, we’ll be releasing the first stable version of TypeScript 5.8. Keep an eye on our iteration plan for target release dates and more if you need to coordinate around that.
Otherwise, our main focus is on developing our next version of TypeScript, and we’ll have the iteration plan available in the coming days (including scheduled release dates). On top of that, we make it easy to use nightly builds of TypeScript on npm, and there is an extension to use those nightly releases in Visual Studio Code.
So give the RC or our nightlies a try! We encourage you to provide any feedback you might have on GitHub.
Happy Hacking!
– Daniel Rosenwasser and the TypeScript Team
The post Announcing TypeScript 5.8 RC appeared first on TypeScript.
]]>Today we are excited to announce the availability of TypeScript 5.8 Beta. To get started using the beta, you can get it through npm with the following command: npm install -D typescript@beta Let’s take a look at what’s new in TypeScript 5.8! Checked Returns for Conditional and Indexed Access Types Consider an API that presents […]
The post Announcing TypeScript 5.8 Beta appeared first on TypeScript.
]]>Today we are excited to announce the availability of TypeScript 5.8 Beta.
To get started using the beta, you can get it through npm with the following command:
npm install -D typescript@beta
Let’s take a look at what’s new in TypeScript 5.8!
Consider an API that presents a set of options to a user:
/**
* @param prompt The text to show to a user.
* @param selectionKind Whether a user can select multiple options, or just a single option.
* @param items Each of the options presented to the user.
**/
async function showQuickPick(
prompt: string,
selectionKind: SelectionKind,
items: readonly string[],
): Promise<string | string[]> {
// ...
}
enum SelectionKind {
Single,
Multiple,
}
The intent with showQuickPick is that it shows a UI element that can allow selecting either a single option or multiple options.
When it does this is determined by the selectionKind parameter.
When selectionKind is SelectionKind.Single, the return type of showQuickPick should be string, and when it is SelectionKind.Multiple, the return type should be string[].
The problem is that the type signature of showQuickPick doesn’t make this clear.
It just says that it eventually returns string | string[] – it could be a string and it could be a string[], but callers have to explicitly check.
In our example below, we might expect shoppingList to have the type string[], but we end up with the more broad string | string[].
let shoppingList = await showQuickPick(
"Which fruits do you want to purchase?",
SelectionKind.Multiple,
["apples", "oranges", "bananas", "durian"],
);
console.log(`Alright, going out to buy some ${shoppingList.join(", ")}`);
// ~~~~
// error!
// Property 'join' does not exist on type 'string | string[]'.
// Property 'join' does not exist on type 'string'.
Instead, we can use a conditional type to make the return type of showQuickPick more precise:
type QuickPickReturn<S extends SelectionKind> =
S extends SelectionKind.Multiple ? string[] : string
async function showQuickPick<S extends SelectionKind>(
prompt: string,
selectionKind: S,
items: readonly string[],
): Promise<QuickPickReturn<S>> {
// ...
}
This works well for callers!
// `SelectionKind.Multiple` gives a `string[]` - works ✅
let shoppingList: string[] = await showQuickPick(
"Which fruits do you want to purchase?",
SelectionKind.Multiple,
["apples", "oranges", "bananas", "durian"],
);
// `SelectionKind.Single` gives a `string` - works ✅
let dinner: string = await showQuickPick(
"What's for dinner tonight?",
SelectionKind.Single,
["sushi", "pasta", "tacos", "ugh I'm too hungry to think, whatever you want"],
);
But what if we try to actually implement showQuickPick?
async function showQuickPick<S extends SelectionKind>(
prompt: string,
selectionKind: S,
items: readonly string[],
): Promise<QuickPickReturn<S>> {
if (items.length < 1) {
throw new Error("At least one item must be provided.");
}
// Create buttons for every option.
let buttons = items.map(item => ({
selected: false,
text: item,
}));
// Default to the first element if necessary.
if (selectionKind === SelectionKind.Single) {
buttons[0].selected = true;
}
// Event handling code goes here...
// Figure out the selected items
const selectedItems = buttons
.filter(button => button.selected)
.map(button => button.text);
if (selectionKind === SelectionKind.Single) {
// Pick the first (only) selected item.
return selectedItems[0];
}
else {
// Return all selected items.
return selectedItems;
}
}
Unfortunately, TypeScript issues an error on each of the return statements.
Type 'string[]' is not assignable to type 'QuickPickReturn<S>'.
Type 'string' is not assignable to type 'QuickPickReturn<S>'.
Until this point, TypeScript required a type assertion to implement any function returning a higher-order conditional type.
if (selectionKind === SelectionKind.Single) {
// Pick the first (only) selected item.
- return selectedItems[0];
+ return selectedItems[0] as QuickPickReturn<S>;
}
else {
// Return all selected items.
- return selectedItems;
+ return selectedItems as QuickPickReturn<S>;
}
This is not ideal because type assertions defeat legitimate checks that TypeScript would otherwise perform.
For example, it would be ideal if TypeScript could catch the following bug where we mixed up each branch of the if/else:
if (selectionKind === SelectionKind.Single) {
// Oops! Returning an array when the caller expects a single item!
return selectedItems;
}
else {
// Oops! Returning a single item when the caller expects an array!
return selectedItems[0];
}
To avoid type assertions, TypeScript 5.8 now supports a limited form of checking against conditional types in return statements. When a function’s return type is a generic conditional type, TypeScript will now use control flow analysis for generic parameters whose types are used in the conditional type, instantiate the conditional type with the narrowed type of each parameter, and relate against that new type.
What does this mean in practice? Well first, let’s look into what kinds of conditional types imply narrowing. To mirror how narrowing operates in expressions, we have to be more explicit and exhaustive about what happens in each branch
type QuickPickReturn<S extends SelectionKind> =
S extends SelectionKind.Multiple ? string[] :
S extends SelectionKind.Single ? string :
never;
Once we’ve done this, everything in our example works.
Our callers have no issue, and our implementation is now type-safe!
And if we try swapping the contents of our if branches, TypeScript correctly flags it as an error!
if (selectionKind === SelectionKind.Single) {
// Oops! Returning an array when the caller expects a single item!
return selectedItems;
// ~~~~~~
// error! Type 'string[]' is not assignable to type 'string'.
}
else {
// Oops! Returning a single item when the caller expects an array!
return selectedItems[0];
// ~~~~~~
// error! Type 'string[]' is not assignable to type 'string'.
}
Note that TypeScript now also does something similar if we’re using indexed access types!
Instead of a conditional type, we can use a type that basically acts as a map from SelectionKind to the return type we want:
interface QuickPickReturn {
[SelectionKind.Single]: string;
[SelectionKind.Multiple]: string[];
}
async function showQuickPick<S extends SelectionKind>(
prompt: string,
selectionKind: S,
items: readonly string[],
): Promise<QuickPickReturn[S]> {
// ...
}
For many users, this will be a more ergonomic way to write the same code.
For more information about this analysis, see the proposal and implementation here!
There are some limitations to this feature.
This special checking only kicks in when a single parameter is associated with the type being checked against in a conditional type or used as a key in an indexed access type.
If using a conditional type, at least two checks must exist, with a terminal branch including never.
That parameter’s type must be generic and have a union type as its constraint.
In other words, the code analysis kicks in for a pattern like the following:
function f<T extends A | B>(x: T):
T extends A ? string :
T extends B ? number :
never
This means these checks will not occur when a specific property is associated with a type parameter. For example, if we rewrote our code above to use an options bag instead of individual parameters, TypeScript would not apply this new checking.
interface QuickPickOptions<S> {
prompt: string,
selectionKind: S,
items: readonly string[]
}
async function showQuickPick<S extends SelectionKind>(
options: QuickPickOptions<S>
): Promise<QuickPickReturn<S>> {
// narrowing won't work correctly here...
}
But workarounds may exist by writing a conditional type that checks against the inner contents.
type QuickPickReturn<O extends QuickPickOptionsBase> =
O extends QuickPickOptionsMultiple ? string[] :
O extends QuickPickOptionsSingle ? string :
never;
interface QuickPickOptionsBase {
prompt: string,
items: readonly string[]
}
interface QuickPickOptionsSingle extends QuickPickOptionsBase {
selectionKind: SelectionKind.Single;
}
interface QuickPickOptionsMultiple extends QuickPickOptionsBase {
selectionKind: SelectionKind.Multiple;
}
async function showQuickPick<Opts extends QuickPickOptionsSingle | QuickPickOptionsMultiple>(
options: Opts
): Promise<QuickPickReturn<Opts>>
These rules may seem like quite a lot to remember, but in practice, most code will not need to leverage these higher-order types. Additionally, while we prefer implementations use this new checking mechanism over type assertions, we do encourage users to keep their APIs simple when possible in the interest of keeping the types written simpler as well. In the meantime, we will continue to explore ways to relax some of these limitations while making the code easy to author.
require() of ECMAScript Modules in --module nodenextFor years, Node.js supported ECMAScript modules (ESM) alongside CommonJS modules. Unfortunately, the interoperability between the two had some challenges.
import CommonJS filesrequire() ESM filesIn other words, consuming CommonJS files from ESM files was possible, but not the other way around. This introduced many challenges for library authors who wanted to provide ESM support. These library authors would either have to break compatibility with CommonJS users, "dual-publish" their libraries (providing separate entry-points for ESM and CommonJS), or just stay on CommonJS indefinitely. While dual-publishing might sound like a good middle-ground, it is a complex and error-prone process that also roughly doubles the amount of code within a package.
Node.js 22 relaxes some of these restrictions and permits require("esm") calls from CommonJS modules to ECMAScript modules.
Node.js still does not permit require() on ESM files that contain a top-level await, but most other ESM files are now consumable from CommonJS files.
This presents a major opportunity for library authors to provide ESM support without having to dual-publish their libraries.
TypeScript 5.8 supports this behavior under the --module nodenext flag.
When --module nodenext is enabled, TypeScript will avoid issuing errors on these require() calls to ESM files.
Because this feature may be back-ported to older versions of Node.js, there is currently no stable --module nodeXXXX option that enables this behavior;
however, we predict future versions of TypeScript may be able to stabilize the feature under node20.
In the meantime, we encourage users of Node.js 22 and newer to use --module nodenext, while library authors and users of older Node.js versions should remain on --module node16 (or make the minor update to --module node18).
For more information, see our support for require("esm") here.
--module node18TypeScript 5.8 introduces a stable --module node18 flag.
For users who are fixed on using Node.js 18, this flag provides a stable point of reference that does not incorporate certain behaviors that are in --module nodenext.
Specifically:
require() of ECMAScript modules is disallowed under node18, but allowed under nodenextnode18, but are disallowed under nodenextSee more at both the --module node18 pull request and changes made to --module nodenext.
--erasableSyntaxOnly OptionRecently, Node.js 23.6 unflagged experimental support for running TypeScript files directly;
however, only certain constructs are supported under this mode.
Node.js has unflagged a mode called --experimental-strip-types which requires that any TypeScript-specific syntax cannot have runtime semantics.
Phrased differently, it must be possible to easily erase or "strip out" any TypeScript-specific syntax from a file, leaving behind a valid JavaScript file.
That means constructs like the following are not supported:
enum declarationsnamespaces and modules with runtime codeimport aliasesSimilar tools like ts-blank-space or Amaro (the underlying library for type-stripping in Node.js) have the same limitations. These tools will provide helpful error messages if they encounter code that doesn’t meet these requirements, but you still won’t find out your code doesn’t work until you actually try to run it.
That’s why TypeScript 5.8 introduces the --erasableSyntaxOnly flag.
When this flag is enabled, TypeScript will only allow you to use constructs that can be erased from a file, and will issue an error if it encounters any constructs that cannot be erased.
class C {
constructor(public x: number) { }
// ~~~~~~~~~~~~~~~~
// error! This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
}
}
For more information, see the implementation here.
--libReplacement FlagIn TypeScript 4.5, we introduced the possibility of substituting the default lib files with custom ones.
This was based on the possibility of resolving a library file from packages named @typescript/lib-*.
For example, you could lock your dom libraries onto a specific version of the @types/web package with the following package.json:
{
"devDependencies": {
"@typescript/lib-dom": "npm:@types/[email protected]"
}
}
When installed, a package called @typescript/lib-dom should exist, and TypeScript will currently always look it up when dom is implied by your settings.
This is a powerful feature, but it also incurs a bit of extra work.
Even if you’re not using this feature, TypeScript always performs this lookup, and has to watch for changes in node_modules in case a lib-replacement package begins to exist.
TypeScript 5.8 introduces the --libReplacement flag, which allows you to disable this behavior.
If you’re not using --libReplacement, you can now disable it with --libReplacement false.
In the future --libReplacement false may become the default, so if you currently rely on the behavior you should consider explicitly enabling it with --libReplacement true.
For more information, see the change here.
In an effort to make computed properties have more predictable emit in declaration files, TypeScript 5.8 will consistently preserve entity names (bareVariables and dotted.names.that.look.like.this) in computed property names in classes.
For example, consider the following code:
export let propName = "theAnswer";
export class MyClass {
[propName] = 42;
// ~~~~~~~~~~
// error!
// A computed property name in a class property declaration must have a simple literal type or a 'unique symbol' type.
}
Previous versions of TypeScript would issue an error when generating a declaration file for this module, and a best-effort declaration file would generate an index signature.
export declare let propName: string;
export declare class MyClass {
[x: string]: number;
}
In TypeScript 5.8, the example code is now allowed, and the emitted declaration file will match what you wrote:
export declare let propName: string;
export declare class MyClass {
[propName]: number;
}
Note that this does not create statically-named properties on the class.
You’ll still end up with what is effectively an index signature like [x: string]: number, so for that use case, you’d need to use unique symbols or literal types.
Note that writing this code was and currently is an error under the --isolatedDeclarations flag;
but we expect that thanks to this change, computed property names will generally be permitted in declaration emit.
Note that it’s possible (though unlikely) that a file compiled in TypeScript 5.8 may generate a declaration file that is not backward compatible in TypeScript 5.7 or earlier.
For more information, see the implementing PR.
TypeScript 5.8 introduces a number of optimizations that can both improve the time to build up a program, and also to update a program based on a file change in either --watch mode or editor scenarios.
First, TypeScript now avoids array allocations that would be involved while normalizing paths. Typically, path normalization would involve segmenting each portion of a path into an array of strings, normalizing the resulting path based on relative segments, and then joining them back together using a canonical separator. For projects with many files, this can be a significant and repetitive amount of work. TypeScript now avoids allocating an array, and operates more directly on indexes of the original path.
Additionally, when edits are made that don’t change the fundamental structure of a project, TypeScript now avoids re-validating the options provided to it (e.g. the contents of a tsconfig.json).
This means, for example, that a simple edit might not require checking that the output paths of a project don’t conflict with the input paths.
Instead, the results of the last check can be used.
This should make edits in large projects feel more responsive.
This section highlights a set of noteworthy changes that should be acknowledged and understood as part of any upgrade. Sometimes it will highlight deprecations, removals, and new restrictions. It can also contain bug fixes that are functionally improvements, but which can also affect an existing build by introducing new errors.
lib.d.tsTypes generated for the DOM may have an impact on type-checking your codebase.
For more information, see linked issues related to DOM and lib.d.ts updates for this version of TypeScript.
--module nodenextImport assertions were a proposed addition to ECMAScript to ensure certain properties of an import (e.g. "this module is JSON, and is not intended to be executable JavaScript code").
They were reinvented as a proposal called import attributes.
As part of the transition, they swapped from using the assert keyword to using the with keyword.
// An import assertion ❌ - not future-compatible with most runtimes.
import data from "./data.json" assert { type: "json" };
// An import attribute ✅ - the preferred way to import a JSON file.
import data from "./data.json" with { type: "json" };
Node.js 22 no longer accepts import assertions using the assert syntax.
In turn when --module nodenext is enabled in TypeScript 5.8, TypeScript will issue an error if it encounters an import assertion.
import data from "./data.json" assert { type: "json" };
// ~~~~~~
// error! Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'
For more information, see the change here
At this point, TypeScript 5.8 is "feature-stable". The focus on TypeScript 5.8 will be bug fixes, polish, and certain low-risk editor features. We’ll have a release candidate available in the next few weeks, followed by a stable release soon after. If you’re interested in planning around the release, be sure to keep an eye on our iteration plan which has target release dates and more.
As a note: while beta is a great way to try out the next version of TypeScript, you can also try a nightly build to get the most up-to-date version of TypeScript 5.8 up until our release candidate. Our nightlies are well-tested and can even be used solely in your editor.
So please try out the beta or a nightly release today and let us know what you think!
Happy Hacking!
– Daniel Rosenwasser and the TypeScript Team
The post Announcing TypeScript 5.8 Beta appeared first on TypeScript.
]]>Today we excited to announce the availability of TypeScript 5.7! If you’re not familiar with TypeScript, it’s a language that builds on JavaScript by adding syntax for type declarations and annotations. This syntax can be used by the TypeScript compiler to type-check our code, and it can also be erased to emit clean, idiomatic JavaScript […]
The post Announcing TypeScript 5.7 appeared first on TypeScript.
]]>Today we excited to announce the availability of TypeScript 5.7!
If you’re not familiar with TypeScript, it’s a language that builds on JavaScript by adding syntax for type declarations and annotations. This syntax can be used by the TypeScript compiler to type-check our code, and it can also be erased to emit clean, idiomatic JavaScript code. Type-checking is helpful because it can catch bugs in our code ahead of time, but adding types to our code also makes it more readable and allows tools like code editors to give us powerful features like auto-completion, refactorings, find-all-references, and more. TypeScript is a superset of JavaScript, so any valid JavaScript code is also valid TypeScript code, and in fact, if you write JavaScript in an editor like Visual Studio or VS Code, TypeScript is powering your JavaScript editor experience too! You can learn more about TypeScript on our website at typescriptlang.org.
To get started using TypeScript through npm with the following command:
npm install -D typescript
Let’s take a look at what’s new in TypeScript 5.7!
For a long time, TypeScript has been able to catch issues when a variable has not yet been initialized in all prior branches.
let result: number
if (someCondition()) {
result = doSomeWork();
}
else {
let temporaryWork = doSomeWork();
temporaryWork *= 2;
// forgot to assign to 'result'
}
console.log(result); // error: Variable 'result' is used before being assigned.
Unfortunately, there are some places where this analysis doesn’t work. For example, if the variable is accessed in a separate function, the type system doesn’t know when the function will be called, and instead takes an "optimistic" view that the variable will be initialized.
function foo() {
let result: number
if (someCondition()) {
result = doSomeWork();
}
else {
let temporaryWork = doSomeWork();
temporaryWork *= 2;
// forgot to assign to 'result'
}
printResult();
function printResult() {
console.log(result); // no error here.
}
}
While TypeScript 5.7 is still lenient on variables that have possibly been initialized, the type system is able to report errors when variables have never been initialized at all.
function foo() {
let result: number
// do work, but forget to assign to 'result'
function printResult() {
console.log(result); // error: Variable 'result' is used before being assigned.
}
}
This change was contributed thanks to the work of GitHub user Zzzen!
There are several tools and runtimes that allow you to run TypeScript code "in-place", meaning they do not require a build step which generates output JavaScript files.
For example, ts-node, tsx, Deno, and Bun all support running .ts files directly.
More recently, Node.js has been investigating such support with --experimental-strip-types (soon to be unflagged!) and --experimental-transform-types.
This is extremely convenient because it allows us to iterate faster without worrying about re-running a build task.
There is some complexity to be aware of when using these modes though.
To be maximally compatible with all these tools, a TypeScript file that’s imported "in-place" must be imported with the appropriate TypeScript extension at runtime.
For example, to import a file called foo.ts, we have to write the following in Node’s new experimental support:
// main.ts
import * as foo from "./foo.ts"; // <- we need foo.ts here, not foo.js
Typically, TypeScript would issue an error if we did this, because it expects us to import the output file.
Because some tools do allow .ts imports, TypeScript has supported this import style with an option called --allowImportingTsExtensions for a while now.
This works fine, but what happens if we need to actually generate .js files out of these .ts files?
This is a requirement for library authors who will need to be able to distribute just .js files, but up until now TypeScript has avoided rewriting any paths.
To support this scenario, we’ve added a new compiler option called --rewriteRelativeImportExtensions.
When an import path is relative (starts with ./ or ../), ends in a TypeScript extension (.ts, .tsx, .mts, .cts), and is a non-declaration file, the compiler will rewrite the path to the corresponding JavaScript extension (.js, .jsx, .mjs, .cjs).
// Under --rewriteRelativeImportExtensions...
// these will be rewritten.
import * as foo from "./foo.ts";
import * as bar from "../someFolder/bar.mts";
// these will NOT be rewritten in any way.
import * as a from "./foo";
import * as b from "some-package/file.ts";
import * as c from "@some-scope/some-package/file.ts";
import * as d from "#/file.ts";
import * as e from "./file.js";
This allows us to write TypeScript code that can be run in-place and then compiled into JavaScript when we’re ready.
Now, we noted that TypeScript generally avoided rewriting paths.
There are several reasons for this, but the most obvious one is dynamic imports.
If a developer writes the following, it’s not trivial to handle the path that import receives.
In fact, it’s impossible to override the behavior of import within any dependencies.
function getPath() {
if (Math.random() < 0.5) {
return "./foo.ts";
}
else {
return "./foo.js";
}
}
let myImport = await import(getPath());
Another issue is that (as we saw above) only relative paths are rewritten, and they are written "naively".
This means that any path that relies on TypeScript’s baseUrl and paths will not get rewritten:
// tsconfig.json
{
"compilerOptions": {
"module": "nodenext",
// ...
"paths": {
"@/*": ["./src/*"]
}
}
}
// Won't be transformed, won't work.
import * as utilities from "@/utilities.ts";
Nor will any path that might resolve through the exports and imports fields of a package.json.
// package.json
{
"name": "my-package",
"imports": {
"#root/*": "./dist/*"
}
}
// Won't be transformed, won't work.
import * as utilities from "#root/utilities.ts";
As a result, if you’ve been using a workspace-style layout with multiple packages referencing each other, you might need to use conditional exports with scoped custom conditions to make this work:
// my-package/package.json
{
"name": "my-package",
"exports": {
".": {
"@my-package/development": "./src/index.ts",
"import": "./lib/index.js"
},
"./*": {
"@my-package/development": "./src/*.ts",
"import": "./lib/*.js"
}
}
}
Any time you want to import the .ts files, you can run it with node --conditions=@my-package/development.
Note the "namespace" or "scope" we used for the condition @my-package/development.
This is a bit of a makeshift solution to avoid conflicts from dependencies that might also use the development condition.
If everyone ships a development in their package, then resolution may try to resolve to a .ts file which will not necessarily work.
This idea is similar to what’s described in Colin McDonnell’s essay Live types in a TypeScript monorepo, along with tshy’s guidance for loading from source.
For more specifics on how this feature works, read up on the change here.
--target es2024 and --lib es2024TypeScript 5.7 now supports --target es2024, which allows users to target ECMAScript 2024 runtimes.
This target primarily enables specifying the new --lib es2024 which contains many features for SharedArrayBuffer and ArrayBuffer, Object.groupBy, Map.groupBy, Promise.withResolvers, and more.
It also moves Atomics.waitAsync from --lib es2022 to --lib es2024.
Note that as part of the changes to SharedArrayBuffer and ArrayBuffer, the two now diverge a bit.
To bridge the gap and preserve the underlying buffer type, all TypedArrays (like Uint8Array and others) are now also generic.
interface Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> {
// ...
}
Each TypedArray now contains a type parameter named TArrayBuffer, though that type parameter has a default type argument so that we can continue to refer to Int32Array without explicitly writing out Int32Array<ArrayBufferLike>.
If you encounter any issues as part of this update, you may need to update @types/node.
This work was primarily provided thanks to Kenta Moriuchi!
When a TypeScript file is loaded in an editor using TSServer (like Visual Studio or VS Code), the editor will try to find the relevant tsconfig.json file that "owns" the file.
To do this, it walks up the directory tree from the file being edited, looking for any file named tsconfig.json.
Previously, this search would stop at the first tsconfig.json file found;
however, imagine a project structure like the following:
project/
├── src/
│ ├── foo.ts
│ ├── foo-test.ts
│ ├── tsconfig.json
│ └── tsconfig.test.json
└── tsconfig.json
Here, the idea is that src/tsconfig.json is the "main" configuration file for the project, and src/tsconfig.test.json is a configuration file for running tests.
// src/tsconfig.json
{
"compilerOptions": {
"outDir": "../dist"
},
"exclude": ["**/*.test.ts"]
}
// src/tsconfig.test.json
{
"compilerOptions": {
"outDir": "../dist/test"
},
"include": ["**/*.test.ts"],
"references": [
{ "path": "./tsconfig.json" }
]
}
// tsconfig.json
{
// This is a "workspace-style" or "solution-style" tsconfig.
// Instead of specifying any files, it just references all the actual projects.
"files": [],
"references": [
{ "path": "./src/tsconfig.json" },
{ "path": "./src/tsconfig.test.json" },
]
}
The problem here is that when editing foo-test.ts, the editor would find project/src/tsconfig.json as the "owning" configuration file – but that’s not the one we want!
If the walk stops at this point, that might not be desirable.
The only way to avoid this previously was to rename src/tsconfig.json to something like src/tsconfig.src.json, and then all files would hit the top-level tsconfig.json which references every possible project.
project/
├── src/
│ ├── foo.ts
│ ├── foo-test.ts
│ ├── tsconfig.src.json
│ └── tsconfig.test.json
└── tsconfig.json
Instead of forcing developers to do this, TypeScript 5.7 now continues walking up the directory tree to find other appropriate tsconfig.json files for editor scenarios.
This can provide more flexibility in how projects are organized and how configuration files are structured.
You can get more specifics on the implementation on GitHub here and here.
Imagine a large codebase with the following structure:
packages
├── graphics/
│ ├── tsconfig.json
│ └── src/
│ └── ...
├── sound/
│ ├── tsconfig.json
│ └── src/
│ └── ...
├── networking/
│ ├── tsconfig.json
│ └── src/
│ └── ...
├── input/
│ ├── tsconfig.json
│ └── src/
│ └── ...
└── app/
├── tsconfig.json
├── some-script.js
└── src/
└── ...
Each directory in packages is a separate TypeScript project, and the app directory is the main project that depends on all the other projects.
// app/tsconfig.json
{
"compilerOptions": {
// ...
},
"include": ["src"],
"references": [
{ "path": "../graphics/tsconfig.json" },
{ "path": "../sound/tsconfig.json" },
{ "path": "../networking/tsconfig.json" },
{ "path": "../input/tsconfig.json" }
]
}
Now notice we have the file some-script.js in the app directory.
When we open some-script.js in the editor, the TypeScript language service (which also handles the editor experience for JavaScript files!) has to figure out which project the file belongs to so it can apply the right settings.
In this case, the nearest tsconfig.json does not include some-script.js, but TypeScript will proceed to ask "could one of the projects referenced by app/tsconfig.json include some-script.js?".
To do so, TypeScript would previously load up each project, one-by-one, and stop as soon as it found a project which contained some-script.js.
Even if some-script.js isn’t included in the root set of files, TypeScript would still parse all the files within a project because some of the root set of files can still transitively reference some-script.js.
What we found over time was that this behavior caused extreme and unpredictable behavior in larger codebases. Developers would open up stray script files and find themselves waiting for their entire codebase to be opened up.
Thankfully, every project that can be referenced by another (non-workspace) project must enable a flag called composite, which enforces a rule that all input source files must be known up-front.
So when probing a composite project, TypeScript 5.7 will only check if a file belongs to the root set of files of that project.
This should avoid this common worst-case behavior.
For more information, see the change here.
--module nodenextWhen importing from a .json file under --module nodenext, TypeScript will now enforce certain rules to prevent runtime errors.
For one, an import attribute containing type: "json" needs to be present for any JSON file import.
import myConfig from "./myConfig.json";
// ~~~~~~~~~~~~~~~~~
// ❌ error: Importing a JSON file into an ECMAScript module requires a 'type: "json"' import attribute when 'module' is set to 'NodeNext'.
import myConfig from "./myConfig.json" with { type: "json" };
// ^^^^^^^^^^^^^^^^
// ✅ This is fine because we provided `type: "json"`
On top of this validation, TypeScript will not generate "named" exports, and the contents of a JSON import will only be accessible via a default.
// ✅ This is okay:
import myConfigA from "./myConfig.json" with { type: "json" };
let version = myConfigA.version;
///////////
import * as myConfigB from "./myConfig.json" with { type: "json" };
// ❌ This is not:
let version = myConfig.version;
// ✅ This is okay:
let version = myConfig.default.version;
See here for more information on this change.
Node.js 22 supports a new API called module.enableCompileCache().
This API allows the runtime to reuse some of the parsing and compilation work done after the first run of a tool.
TypeScript 5.7 now leverages the API so that it can start doing useful work sooner.
In some of our own testing, we’ve witnessed about a 2.5x speed-up in running tsc --version.
Benchmark 1: node ./built/local/_tsc.js --version (*without* caching)
Time (mean ± σ): 122.2 ms ± 1.5 ms [User: 101.7 ms, System: 13.0 ms]
Range (min … max): 119.3 ms … 132.3 ms 200 runs
Benchmark 2: node ./built/local/tsc.js --version (*with* caching)
Time (mean ± σ): 48.4 ms ± 1.0 ms [User: 34.0 ms, System: 11.1 ms]
Range (min … max): 45.7 ms … 52.8 ms 200 runs
Summary
node ./built/local/tsc.js --version ran
2.52 ± 0.06 times faster than node ./built/local/_tsc.js --version
For more information, see the pull request here.
This section highlights a set of noteworthy changes that should be acknowledged and understood as part of any upgrade. Sometimes it will highlight deprecations, removals, and new restrictions. It can also contain bug fixes that are functionally improvements, but which can also affect an existing build by introducing new errors.
lib.d.tsTypes generated for the DOM may have an impact on type-checking your codebase.
For more information, see linked issues related to DOM and lib.d.ts updates for this version of TypeScript.
TypedArrays Are Now Generic Over ArrayBufferLikeIn ECMAScript 2024, SharedArrayBuffer and ArrayBuffer have types that slightly diverge.
To bridge the gap and preserve the underlying buffer type, all TypedArrays (like Uint8Array and others) are now also generic.
interface Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> {
// ...
}
Each TypedArray now contains a type parameter named TArrayBuffer, though that type parameter has a default type argument so that users can continue to refer to Int32Array without explicitly writing out Int32Array<ArrayBufferLike>.
If you encounter any issues as part of this update, such as
error TS2322: Type 'Buffer' is not assignable to type 'Uint8Array<ArrayBufferLike>'.
error TS2345: Argument of type 'Buffer' is not assignable to parameter of type 'Uint8Array<ArrayBufferLike>'.
error TS2345: Argument of type 'ArrayBufferLike' is not assignable to parameter of type 'ArrayBuffer'.
error TS2345: Argument of type 'Buffer' is not assignable to parameter of type 'string | ArrayBufferView | Stream | Iterable<string | ArrayBufferView> | AsyncIterable<string | ArrayBufferView>'.
then you may need to update @types/node.
You can read the specifics about this change on GitHub.
TypeScript now has a more consistent behavior for methods in classes when they are declared with non-literal computed property names. For example, in the following:
declare const symbolMethodName: symbol;
export class A {
[symbolMethodName]() { return 1 };
}
Previously TypeScript just viewed the class in a way like the following:
export class A {
}
In other words, from the type system’s perspective, [symbolMethodName] contributed nothing to the type of A
TypeScript 5.7 now views the method [symbolMethodName]() {} more meaningfully, and generates an index signature.
As a result, the code above is interpreted as something like the following code:
export class A {
[x: symbol]: () => number;
}
This provides behavior that is consistent with properties and methods in object literals.
Read up more on this change here.
any Errors on Functions Returning null and undefinedWhen a function expression is contextually typed by a signature returning a generic type, TypeScript now appropriately provides an implicit any error under noImplicitAny, but outside of strictNullChecks.
declare var p: Promise<number>;
const p2 = p.catch(() => null);
// ~~~~~~~~~~
// error TS7011: Function expression, which lacks return-type annotation, implicitly has an 'any' return type.
See this change for more details.
We’ll have details of our plans for the next TypeScript release soon, but if you’re looking for the latest fixes and features, we make it easy to use nightly builds of TypeScript on npm, and we also publish an extension to use those nightly releases in Visual Studio Code.
Otherwise, we hope that TypeScript 5.7 makes coding a joy for you. Happy Hacking!
– Daniel Rosenwasser and the TypeScript Team
The post Announcing TypeScript 5.7 appeared first on TypeScript.
]]>