Consider the example Object below:
let obj1: Obj = {
'key1': { default: 'hello', fn: (val:string) => val },
'key2': { default: 123, fn: (val:number) => val },
// this should throw an error, because the types of default and fn do not match
'key3': { default: true, fn: (val:string) => val }
}
An ideal Interface for this object would be as follows:
interface Obj {
[key: string]: { default: T, fn: (val:T) => any }
}
This however does not work due to lack of definition for T
.
To address this issue, one could attempt the following solution:
interface ObjValue<T> {
default: T;
fn: (val:T) => any;
}
interface Obj {
[key: string]: ObjValue<?>
}
Unfortunately, defining the generic type for ObjValue
also presents challenges.
If one uses ObjValue<any>
, then everything is typed as any
, which is not desired.
The goal is to ensure that the type of default
and parameter type of fn
always match. Is there a solution to achieve this, or is it impossible?