背景 今回もmattさんの動画をまとめていく
TypeScript Tip #5
概要 型推論された型に対してextendsを使用するまとめていく。
本題 実際のサンプルコードは以下。 getDeepValue関数の引数にオブジェクトを渡して、そこから型推論をさせている。
第2引数、第3引数のオブジェクトのキーを指定して、最終的なバリューを取得できるような関数を作成する。
export const getDeepValue = < Obj, FirstKey extends keyof Obj, SecondKey extends keyof Obj[FirstKey] >( obj: Obj, firstKey: FirstKey, secondKey: SecondKey ): Obj[FirstKey][SecondKey] => { return obj[firstKey][secondKey] } const obj = { foo: { a: true, b: 2 }, bar: { c: 'cool', d: 2 } } console.log(getDeepValue(obj, 'bar', 'd')) 引数の第2引数FirstKeyは型推論されたObjに制約を設けている。 FirstKey extends keyof { foo: { a: boolean; b: number; }; bar: { c: string; d: number; }; } 🔽 FirstKey extends "foo" | "bar" よって、FirstKeyはfooかbarのどちらかになる。