Below is the code snippet I am working with:
const Settings = {
setting1: 10,
setting2: true,
};
type S = typeof Settings;
function Process<M extends keyof S>(input: { option: M; value: S[M] }) { }
If I try to call Process
with an incorrect type for the parameter, like this:
Process({ option: 'setting2', value: 23 });
// ^ Error: value should be boolean, which it isn't
Query:
I am wondering if it's feasible to generate a new type dynamically based on the argument type of a function, similar to this:
type T5<M extends keyof S> = {
option: M;
value: {
setting1: number;
setting2: boolean;
}[M];
}
function ProcessNew<M extends keyof S>(input: T5<M>): void { }
ProcessNew({ option: 'setting2', value: 42 });
// ^ Error: value should be boolean, which it isn't
Rather than defining T5
explicitly, I want it to be created dynamically, taking into account the function's argument type.
I attempted the following approach, but lost type safety for the second parameter:
function NewFunction(arg: Parameters<typeof Process>[0]): void { }
NewFunction({ option: 'setting2', value: 23 });
// ^ No Error, which is a problem
The type of the parameter in this case becomes :
arg: {
option: "setting1" | "setting2";
value: number | boolean;
}
I still want to ensure that the type of the second parameter (in this scenario, value
) is restricted based on the first parameter.
To clarify further, when we use type T6 = typeof Process
, we obtain the following type:
type T6 = <M extends "setting1" | "setting2">(input: {
option: M;
value: {
setting1: number;
setting2: boolean;
}[M];
}) => void
... Is there a way to derive a new type like below from the above type? :
type T5<M extends "setting1" | "setting2"> = {
option: M;
value: {
setting1: number;
setting2: boolean;
}[M];
}