I like the tricks :) – Kasia
Ensure at compile time that you are digging keys that exist in the object.
const dig = ( key1: string, key2: string, obj: Record<string, Record<string, unknown>> ) => obj[key1][key2] const obj = { a: { b: 1 }} dig('a', 'b', obj) // 1 dig('z', 'x', obj) // ⛔️ BOOM
const dig = < Key1 extends string, Key2 extends string, Object extends Record<Key1, Record<Key2, unknown>> >(key1: Key1, key2: Key2, obj: Object) => obj[key1][key2] const obj = { a: { b: 1 }} dig('a', 'b', obj) // 1 dig('z', 'x', obj) // ✅ Does not compile
Crafted with 💛 by Riccardo