He llegado hasta aquí: lo que parece funcionar
function test<types extends Record<string,any>>(dict: dictionary<types>){} type dictionary<types extends Record<string, any>> = { [key in keyof types]: { bar?: types[key]; foo?: (value:types[key])=>true; }; }; test({ key1:{ bar: 2, foo: (input:number)=>true, }, key2:{ bar: 'hello' foo: (input: number)=>true, // Error! "input" needs to be string } }) ¡PERO! También necesito una referencia de tipo genérico al parámetro dict . Y por alguna razón, esto no funciona.
function test2< types extends Record<string,any>, dictionary extends dictionary2<types> // <-- Added a generic type >(dict: dictionary){} // Same as above type dictionary2<types extends Record<string, any>> = { [key in keyof types]: { bar?: types[key]; foo?: (value:types[key])=>true; }; }; // Same as above test2({ key1:{ bar: 2, foo: (input: number)=>true, }, key2:{ bar: 'hello', foo: (input:number)=>true,// Should be an Error (but isn't)! "input" needs to be string }Podrías hacer esto:
function test2<T extends Record<string, unknown>>(dict: Dictionary<T>) { } type Dictionary<T> = { [key in keyof T]: { bar?: T[key]; foo?: (value: T[key]) => true; }; } // Same as above test2({ key1: { bar: 2, foo: (input: number) => true, }, key2: { bar: 'hello', foo: (input: number) => true, // Actual error } });Cambie el alcance de la inferencia para que se infieran los types y se escriba dict en función de esa inferencia en lugar de un segundo parámetro de tipo, es decir,
function test2< types extends Record<string,any> >(dict: dictionary2<types>){}Zona de juegos de trabajo aquí .
EDITAR: Ejemplo de uso con mayúsculas convencionales
function test2< T, >(dict: Dictionary<T>){ type FullDictionary = Dictionary<T> // can't you just use this in your function? } type Dictionary<T extends Record<string, any>> = { [K in keyof T]: DictionaryEntry<T[K]> } type DictionaryEntry<T> = { bar?: T foo?: (value:T)=>true } test2({ key1:{ bar: 2, foo: (input: number)=>true, }, key2:{ bar: 'hello', foo: (input:number)=>true } })