TypeScript の constアサーション
レベル 5420 打鍵
as const はオブジェクトや配列を深く読み取り専用にし、string ではなく "/about" のようなリテラル型を保ちます。これにより navigate は実在するルートの値だけを受け付けます。
TypeScript のコード
// as const がなければ、各値の型はただの string になる1const routes = {2 home: "/",3 about: "/about",4 users: "/users"// プロパティを readonly にし、"/" のようなリテラル型にする5} as const;// { readonly home: "/"; readonly about: "/about"; readonly users: "/users" } になる6type Routes = typeof routes;// "home" | "about" | "users" になる7type RouteKeys = keyof Routes;// "/" | "/about" | "/users" になる8type RouteValues = Routes[RouteKeys];// 実在するパスだけを受け付ける。navigate("/home") はコンパイルできない9function navigate(path: RouteValues): void {10 console.log(`Navigating to: ${path}`);11}// as const を付けた配列は readonly のタプルになる12const tuple = [1, "hello", true] as const;// readonly [1, "hello", true] になる(TupleType は実行時には使われない)13type TupleType = typeof tuple;// 「Navigating to: /」を表示する14navigate(routes.home);// 「Navigating to: /about」を表示する15navigate(routes.about);// 「Tuple: 1, hello, true」を表示する16console.log(`Tuple: ${tuple.join(", ")}`);実行結果
Navigating to: / Navigating to: /about Tuple: 1, hello, true
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この TypeScript のコードで打つ記号と、出てくる回数です。
;× 10"× 10:× 7(× 6)× 6=× 6,× 5.× 5{× 4}× 4