Honestly, I had a bit of a hard time to define a proper title for this question.
I want to write a function that I can pass an Interface as a Generic and a string as a parameter which is a Key of that Interface. This returns a function that can receive a single parameter that should be properly typed (Interface[Key]).
export const createFunction = <T extends Record<string, any>>(
key: keyof T,
): (value: ?????) => void => (value) => {
// Do something with value
};
I tried playing around with a function type but wasn't able to make it work
type Getter<T extends Record<string, any>> = <Key extends keyof T>(
key: Key,
) => (value: T[Key]) => void;
CodePudding user response:
I'm not 100% sure I understand the question - is this what you're after?
export const createSetterFactory = <T extends Record<string, any>>() => {
return <K extends keyof T>(key: K) => (value: T[K]) => {
// Do something with value
}
};
interface MyInterface {
foo: number;
}
// pass Interface as a Generic
const mySetterFactory = createSetterFactory<MyInterface>();
// a string as a parameter which is a Key of that Interface
const fooSetter = mySetterFactory('foo');
// Do something with the value of foo
fooSetter(123);