Since ES6 introduced modules in 2015, work has begun to bring the JavaScript and TypeScript ecosystems to the native module format. Early use was mostly limited to scripting, with build tools like Webpack and transpilers like TypeScript turning code into modules that would run in various environments. As the module format has improved in recent years, browsers natively support ESM loading, and Node.js 16 now supports it as well. TypeScript 4.7 helps us move closer to a world where all JavaScript is built and used as an ESM. Daniel Rosenwasser, TypeScript Program Manager, explains:
In recent years, Node.js has been working on supporting ECMAScript Modules (ESM). This was a very difficult feature, as the Node.js ecosystem is built on a different module system called CommonJS (CJS). The interaction between the two brings great challenges, with many new features to juggle.
TypeScript 4.7 adds two new module settings: node16 and nodenext. Through the use of package.json’s “type”: “module”, Node.js determines whether .js files are interpreted as ESM or CommonJS modules. ESM supports core features such as import/export statements and top-level async/await. ESM-relative import paths need full file extensions in the path, and various techniques used by CommonJS modules are not supported, such as require and top-level module. Node.js supports two new file extensions for modules always ESM or CJS, .mjs and .cjs, so TypeScript has added correspondingly, .mts and .cts. These releases add more than just Node.js ESM support. Control flow analysis for bracketed element accesses helps to limit the types of element accesses when the indexed keys are literal types and unique symbols. The –strictPropertyInitialization flag now controls that computed properties are initialized before the end of a construction body. TypeScript 4.7 also supports more granular type inference from functions inside objects and arrays. New support for instantiation expressions allows generics to be restricted during instantiation. TypeScript 4.8 adds several correctness and consistency improvements to the –strictNullChecks function. Improvements to intersection and union types help TypeScript narrow down its type definitions. Also in TypeScript 4.8, the TypeScript converter can better infer types within template string types. TypeScript transpiler enhancements with –build, –watch, and –incremental reduce typical transpiler times by 10-25%. These two versions added dozens of other improvements and bug fixes. Read the full release notes to learn more about each release. The official release of TypeScript 4.8 is expected in mid-late August, in time for TypeScript to be 10 years old in October! TypeScript is open source software available under the Apache 2 License. Contributions and comments are encouraged through the TypeScript GitHub project and should follow the TypeScript contribution guidelines and Microsoft’s Open Source Code of Conduct.