
TypeScript 7.1 Beta
Today we’re excited to announce the beta release of TypeScript 7.1!
以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。
Today we’re excited to announce the beta release of TypeScript 7.1!
npm install -D typescript@beta
Let’s take a look at what’s new in TypeScript 7.1!
Import attributes are metadata that are attached to import statements. Typically, they’re meant to instruct runtimes and bundlers on how to interpret the content of an import, as well as the shape of the resulting module. For example,
import myData from "./data/someData.json" with { type: "json" };
Everything in the object following the with keyword is an import attribute. Environments like browsers can’t simply decide how to deal with an import based on file name extensions like .json. Specifying type: "json" tells whatever runtime that someData.json needs to be interpreted as a JSON file, parsed out, and provided via a default import (in our example above, that’s myData).
The type attribute has become the de facto way for runtimes to customize this behavior. ECMAScript (JavaScript) has a proposal that allows code to specify type: "text", which returns the import’s contents as a string.
import readme from "../README.md" with { type: "text" };
console.log(readme);
There is also a proposal for type: "bytes" to return a Uint8Array of raw bytes.
import { pngToPixels, boxBlur } from "./photoUtils.js";
import photo from "./myPhoto.png" with { type: "bytes" }; const blurryPhoto = boxBlur(pngToPixels(photo));
Browsers have also allowed importing CSS files as CSSStyleSheets with type: "css" for a few years now.
import someTheme from "./themes/someCoolTheme.css" with { type: "css" };
document.adoptedStyleSheets.push(someTheme);
To support importing these files, people might use ambient module declarations in TypeScript using a wildcard pattern (e.g. *.css).
// You can write this in a global .d.ts file with no import statements.
declare module "*.css" { const content: CSSStyleSheet; export default content; }
declare module "*.txt" { const content: string; export default content; }
declare module "*.md" { const content: string; export default content; }
declare module "*.bin" { const content: Uint8Array; export default content; }
This is okay, but it doesn’t work for all environments as it doesn’t account for import attributes at all.
You might ask why this is an issue – at first glance, it seems like the only problem is that it just allows people to accidentally leave off an import attribute.
// ❌ oops, forgot an import attribute import readme from "../README.md";
// ✅ what we were supposed to write import readme from "../README.md" with { type: "text" };
But that is still a problem worth fixing. Another issue is that it becomes repetitive. With import attributes, the entire issue is that the runtime cares about the attributes, not the file extension. We shouldn’t have to re-declare a pattern for both .txt and .md files if both were going to use type: "text".
But a major issue is that runtime environments may support different import attributes entirely, and may act differently depending on whether they’re present. For example, bundlers might use a build-time feature called CSS Modules as the default behavior when importing .css files, but specifying the browser-supported type: "css" in the import statement will override this behavior and ensure the .css file is brought in as a CSSStyleSheet object.
That’s why TypeScript 7.1 introduces support for import attributes in ambient module declarations. You can now declare the following in your TypeScript projects, get an error if you try to import a file without the required import attributes, and get the correct type based on the import attributes.
declare module "*" with { type: "css" } { const content: CSSStyleSheet; export default content; }
declare module "*" with { type: "text" } { const content: string; export default content; }
declare module "*" with { type: "bytes" } { const content: Uint8Array; export default content; }
Note that imports matching these declarations are not validated against files on disk. As is currently the behavior when an import matches an ambient module declaration, failed lookups will be reported at runtime or during a bundler’s build process.
Also note that these declarations are not shipped as part of the TypeScript built-in libraries. We recommend libraries not include them in their published packages, and end-users will need to declare them in their own projects if necessary. That will provide end-users with flexibility on how the global scope is configured (e.g. lib.dom.d.ts versus @types/node) and will prevent conflicts with built-in declarations in the future.
For more information, see our implementing pull request here.
Source phase imports are a proposed new feature in ECMAScript. The feature introduces a new source modifier/keyword that follows the import keyword. Only default imports can be written with import source.
import source SomeModule from "some-module";
The idea with this feature is that when we use import source, we’ll get back an object that represents the module after it’s been parsed and analyzed by the runtime, but before its imports have been loaded (and therefore, before they have been validated or linked against other modules, and before any code contained in the module can run). This object on its own is kind of “inert” – it’s an instance of something called an AbstractModuleSource which is eventually meant to be imported or instantiated.
For WebAssembly (wasm) imports, that object will be an instance of a WebAssembly.Module. What’s useful with these objects is that they can be passed directly into WebAssembly.instantiate.
import source SuperFastThing from "./super-fast-thing.wasm"; import { WASI } from "node:wasi";
const wasi = new WASI({ /.../ }); const fastThingInstance = await WebAssembly.instantiate(SuperFastThing, { wasi_snapshot_preview1: wasi.wasiImport });
wasi.start(fastThingInstance);
WebAssembly source imports are already supported in recent versions of Node.js.
At the moment, you can’t do much with a source import of a JavaScript file. The spirit of the proposal implies at some point we might be able to pass a JavaScript module source directly into an import() call.
import source SomeModule from "./someModule.js"; const moduleInstance = await import(SomeModule);
Another part of the idea with JavaScript source imports is that, over time, we may gain other features that will allow us to be able to customize behavior around how modules are loaded and instantiated, similar to how we did with WebAssembly.instantiate above. But we’re not there yet, and in fact, many environments and tools still don’t currently support JavaScript source imports in the first place.
Source imports aren’t limited to import statements though. You can also perform a dynamic source import as well via the import.source meta-property function.
const SuperFastThing = await import.source("./super-fast-thing.wasm"); const fastThingInstance = await WebAssembly.instantiate(SuperFastThing, { // ... });
Source imports retain identity. That means you can use them in Maps and Sets, or compare against them reliably.
// Note that WebAssembly.instantiate always returns a distinct object.
import source source1 from "./plugin.wasm"
import source source2 from "./plugin.wasm"
const source3 = await import.source("./plugin.wasm");
console.log(source1 === source2); // true console.log(source2 === source3); // true
When using import source, every imported module has the type AbstractModuleSource, a new global type in lib.esnext.d.ts. You must have an appropriate --module setting (i.e. esnext, nodenext, or preserve) to use source imports, as well as the appropriate esnext option in --lib or --target.
This feature was implemented thanks to the work of Oleksandr Tarasiuk.
TypeScript 7.1 now supports es2026 as a stable --target and --lib option. Only lib additions are significant, as declarations have been added, or moved from esnext as proposed features have stabilized in ECMAScript 2026.
The work of creating the new targets, as well as many of the declaration files themselves, was done thanks to Oleksandr Tarasiuk.
--lib esnext now includes a few proposed library methods in ECMAScript including:
Support for these Promise methods and Iterator methods was provided thanks to Oleksandr Tarasiuk.
TypeScript 7.1 ships a new API that allows building powerful tools and utilities using our syntactic and semantic analyses.
Rather than exposing a monolithic API, TypeScript 7.1 is organized into several entry points, each serving a specific purpose.
Here’s an example of how to conduct a simple compilation using the TypeScript 7.1 API, with filenames and compiler options passed explicitly on the command line. Unlike tsc, this example does not discover or load a tsconfig.json file and does not support --project.
// Compile explicit filenames using command-line compiler options.
import { API, formatDiagnosticsWithColorAndContext, type Diagnostic } from "typescript/sync";
using api = new API(); const reportErrors = (diagnostics: readonly Diagnostic[]) => { console.log(formatDiagnosticsWithColorAndContext(diagnostics, api)) };
// Parse command-line filenames and compiler options, report any errors. const commandLineArgs = process.argv.slice(2); const parsedCommandLine = api.parseCommandLine(commandLineArgs); if (parsedCommandLine.errors.length > 0) { reportErrors(parsedCommandLine.errors); process.exit(); }
// Create the program by resolving and parsing all files in the entry point. using program = api.createProgram(parsedCommandLine.fileNames, parsedCommandLine.options);
// Collect and report any diagnostics from the program before emitting. // You can customize whether any of these block reporting errors in subsequent passes if desired. const diagnostics = [ ...program.getGlobalDiagnostics(), ...program.getProgramDiagnostics(), ...program.getSyntacticDiagnostics(), ...program.getSemanticDiagnostics(), ]; if (diagnostics.length > 0) { reportErrors(diagnostics); }
// Emit files - this respects the noEmitOnError option,
// so nothing will be emitted if an earlier step reported errors.
const emitResult = program.emit();
if (emitResult.diagnostics.length > 0) {
reportErrors(emitResult.diagnostics);
}
Notice the using keyword in our declarations above. You might not be familiar with using since it’s somewhat new in JavaScript, but don’t fret.
API instances and Program instances are both Disposable objects. When we ask to create them, TypeScript allocates memory and does book-keeping to make sure they stick around between the Go and JavaScript runtimes; however, when we are done with them, we can’t just let the garbage collector deal with them or else we’ll leak on the Go side. Instead, we have to do one of the following:
After a program is disposed, we won’t be able to use it again.
Above, we modeled a straight-line “batch” compilation with the API; but lots of workflows with TypeScript are oriented around changes that might occur over time. Rather than build up the entire world every time we need, TypeScript is able to model transitions in state with new file updates – either on disk or as a user types.
Core to the API is the concept of a snapshot. A snapshot is a version of all the projects and programs at a point in time. We can always create a fresh snapshot with all the information we need with api.createSnapshot, but we can also derive a new snapshot from a prior one with the snapshot.update(/.../). This can often save a lot of work, both in sending over all the original information and having the compiler rebuild the world.
import { ScriptTarget } from "typescript/ast"; import { createFileSystemLayer, createFileSystemWithLib } from "typescript/fs"; import { API } from "typescript/sync"; import { resolve } from "node:path";
const fileName = resolve("snapshot-exa
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。