TypeScript 5.3 has been officially released.
Main changes
-
Recent updates to support import attributes proposal
- Provides stable support for Import Types
resolution-mode
- Provide support for all Module Modes
resolution-mode
-
switch (true)
Narrowing -
Narrowing On Comparisons to Booleans
-
super
Check property access to instance fields -
Interactive Inlay Hints for types
-
Skip JSDoc parsing for optimization
-
merge
tsserverlibrary.js
andtypescript.js
One use case for import attributes is to provide the runtime with information about the module's expected format.
// We only want this to be interpreted as JSON,
// not a runnable/malicious JavaScript file with a `.json` extension.
import obj from "./something.json" with { type: "json" };
TypeScript does not check the contents of these properties because they are host-specific, so they are not checked and are simply left to the browser and runtime to handle them (potentially with errors).
// TypeScript is fine with this.
// But your browser? Probably not.
import * as foo from "./foo.js" with { type: "fluffy bunny" };
Dynamic import () calls can also use the import attribute via the second parameter.
const obj = await import("./something.json", {
with: { type: "json" }
});
The expected type of the second argument is ImportCallOptions
defined by a type named , which by default only expects a property to be called with
.
Note that import properties evolved from the earlier proposal for "import assertions", which was implemented in TypeScript 4.5. The most obvious difference is the use of with
keywords instead of assert
keywords. But the less obvious difference is that the runtime is now free to use properties to guide the parsing and interpretation of import paths, whereas import assertions can only assert certain characteristics after the module is loaded.
Over time, TypeScript will deprecate the old import assertion syntax in favor of the recommended import property syntax. Existing code using assert should be migrated to the with keyword. New code that requires imported properties should only use with
the keyword.
switch (true)
Narrowing
TypeScript 5.3 can perform narrowing based on conditions switch (true)
in each case
clause.
function f(x: unknown) {
switch (true) {
case typeof x === "string":
// 'x' is a 'string' here
console.log(x.toUpperCase());
// falls through...
case Array.isArray(x):
// 'x' is a 'string | any[]' here.
console.log(x.length);
// falls through...
default:
// 'x' is 'unknown' here.
// ...
}
}