TypeScript 5.3
2023 年 11 月 20 日に TypeScript 5.3 がリリースされました。
https://devblogs.microsoft.com/typescript/announcing-typescript-5-3/
新たな構文のサポートに加えて、JSDoc 解析をスキップすることによる最適化やパッケージの重複を避けることによるパッケージサイズの削減なども行われました。
Import Attributes
Stage 3 の Import Attributes がサポートされました。
https://github.com/tc39/proposal-import-attributes
これによりモジュールの形式をランタイムに提供できるようになります。
tsx
import obj from "./something.json" with { type: "json" };
import * as foo from "./foo.js" with { type: "fluffy bunny" };
const obj = await import("./something.json", {
with: { type: "json" },
});switch(true) Narrowing
switch (true)内の各case句に基づいて型の絞り込みをできるようになりました。
tsx
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.
// ...
}
}Narrowing On Comparisons to Booleans
true または false と直接比較した場合でも、絞り込みが出来るようになりました。
tsx
interface A {
a: string;
}
interface B {
b: string;
}
type MyType = A | B;
function isA(x: MyType): x is A {
return "a" in x;
}
// <=5.2
function someFn(x: MyType) {
if (isA(x)) {
console.log(x.a); // works!
}
}
// <=5.2
function someFn(x: MyType) {
if (isA(x) === true) {
console.log(x.a); // not works
}
}
// 5.3
function someFn(x: MyType) {
if (isA(x) === true) {
console.log(x.a); // works!
}
}