TypeScript の typeof型演算子
レベル 3278 打鍵
typeof型演算子は値の推論された型から型を作成します。
TypeScript のコード
// ふつうのオブジェクト。型はTypeScriptが推論する1const config = {2 host: "localhost",3 port: 3000,4 debug: true5};// Configは{ host: string; port: number; debug: boolean }になる6type Config = typeof config;// その形のオブジェクトなら何でも受け取る7function printConfig(c: Config): void { // host:portとdebugの値を表示する8 console.log(`${c.host}:${c.port} (debug: ${c.debug})`);9}// 「localhost:3000 (debug: true)」を表示する10printConfig(config);// 同じ形の別のオブジェクト:「api.example.com:8080 (debug: false)」11printConfig({ host: "api.example.com", port: 8080, debug: false });実行結果
localhost:3000 (debug: true) api.example.com:8080 (debug: false)
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この TypeScript のコードで打つ記号と、出てくる回数です。
:× 10.× 6{× 6}× 6;× 5(× 5)× 5,× 4"× 4$× 3