Is there a way to enhance the safety of this function even further?
Consider this object/shape:
export const initialState: State = {
foods: {
filter: '',
someForm: {
name: '',
age: 2,
},
someFormWithoutAnAge: {
name: '',
},
}
};
declare function pickAForm<R extends keyof State, S extends keyof State[R]>(key1: R, key2: S): void;
The current function pickAForm
ensures type safety with examples like pickAForm("foods", "someForm")
working as expected and catching errors like
pickAForm("foods", "somePropertyThatDoesntExist")
Now, I want to enforce an additional safety measure where selections must have a specific shape. For instance, selecting someForm
should be valid, whereas choosing someFormWithoutAnAge
should result in failure because it lacks an age property. This can be achieved by introducing:
declare function pickAFormWithAge<R extends keyof State, S extends keyof State[R], T extends State[R][S] & {age: number}>(key1: R, key2: S): void;
The challenge now is implementing this enhancement. To clarify:
pickAFormWithAge('foods', 'someForm') // Should pass
pickAFormWithAge('foods', 'someFormWithoutAge') // Should fail, as it doesn't match the required shape {age: number}
pickAFormWithAge('foods', 'blah') // Should fail because 'blah' is not a valid key