TypeScript v4.5
2021/11/17
The Awaited Type and Promise Improvements
従来は、
target
に対するpolyfill感覚で lib
を指定していた
これは
lib
の指定を見て、
この辺のやつを自動で読み込んでいた
以下2つの問題がある
lib
のversion指定ができない
そのため、TypeScriptをupgradeすると、勝手に lib
のversionも上がる
例えば、 dom
は頻繁に更新されているため、ぶっ壊れる可能性がある
dependenciesとの組み合わせが困難になることがある
dependenciesの1つが dom
に依存していると、 dom
の指定が強制される
v 4.5で、この lib
をoverrideする方法が提供された
例えば、 lib
に hoge
が指定された場合、
まず最初に node_modules/@typescript/lib-hoge/
を探しに行く
その次に、 hoge.es2015.d.ts
などが探される
従来は、問答無用で hoge.es2015.d.ts
などが読み込まれていた
dependenciesに追記することで、この指定ができる
package.json{
"dependencies": {
"@typescript/lib-dom": "npm:@types/web"
}
}
この仕組みにより以下のことができるようになった
lib
のversionを固定できる
lib
を自分好みに入れ替えることができる
標準libraryを上書きで他のものに変えられる
Types for the DOM and most web-related APIs
Template String Types as Discriminants
template litearal typesでguardできる
tsexport interface Success {
type: `${string}Success`;
body: string;
}
export interface Error {
type: `${string}Error`;
message: string;
}
export function handler(r: Success | Error) {
if (r.type === "HttpSuccess") {
let token = r.body; // v4.4だとSuccessに絞り込まれていないのでerror
}
}
tsconfigの module
に es2022
が指定できるようになった
top-level awaitとか使える
Tail-Recursion Elimination on Conditional Types
Conditional Typesで定義する際に、末尾再帰で書くと、ネストを深くできる
Disabling Import Elision
一見未使用に見える宣言を、削除しないようにする
type Modifiers on Import Names
after.tsimport { Foo1, type Foo2 } from "foo";
Private Field Presence Checks
private property #hoge
の存在チェック
#hoge in object
という式を評価できるようになった
tsclass Person {
#name;
constructor(name: string) {
this.#name = name;
}
equals(other: unknown) {
return (
other != null &&
typeof other === 'object' &&
#name in other &&
this.#name === other.#name
);
}
}
class Person2 {
#name;
constructor(name: string) {
this.#name = name;
}
}
console.log(new Person("hoge").equals(new Person("hoge"))); // true
console.log(new Person("hoge").equals(new Person2("hoge"))); // false
①の部分は、
「 #name
を持っているかどうか」という構造的部分型的なものではなく、
「 Person
の #name
を持っているか」というbranded type的な評価になる
だから #hoge in object
という式のみで、そのinstanceであることを確定できる
tsclass Person {
#name;
constructor(name: string) {
this.#name = name;
}
hoge(other: object) {
if (#name in other) { // これで`Person`であることが確定できる
const perosn = other // 型もちゃんとPersonになっている
}
}
}
Import Assertions
tsimport obj from "./something.json" assert { type: "json" };
Const Assertions and Default Type Arguments in JSDoc
JSDocでconst assersionと同等のことが書けるようになった
tslet b = /** @type {const} */ ({ prop: "hello" });
というか、この辺もTypeScriptの責務なのか

Faster Load Time with realPathSync.native
windowsで読み込みがちょっと速くなった
New Snippet Completions
補完能力の向上
JSXのタグの属性補完をする時に、値の型を見て、
hoge="|"
とするか
文字列型の場合
hoge={|}
とするかを分けてくれる
数値型とかの場合
でもこれ、文字列でも変数入れることあるしな?

Better Editor Support for Unresolved Types
型が見つからなかった時のhover時に any
ではなく /*unresolved*/ any
と出る
Experimental Nightly-Only ECMAScript Module Support in Node.js
betaで入れようとしたが保留になったやつか
v4.7で入るんだっけ