老實說,我很難為這個問題定義一個合適的標題。
我想撰寫一個函式,我可以將介面作為泛型傳遞,將字串作為引數傳遞,該引數是該介面的鍵。這將回傳一個函式,該函式可以接收應正確鍵入的單個引數 (Interface[Key])。
export const createFunction = <T extends Record<string, any>>(
key: keyof T,
): (value: ?????) => void => (value) => {
// Do something with value
};
我嘗試使用函式型別,但無法使其作業
type Getter<T extends Record<string, any>> = <Key extends keyof T>(
key: Key,
) => (value: T[Key]) => void;
uj5u.com熱心網友回復:
我不是 100% 確定我理解這個問題 - 這就是你所追求的嗎?
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/433052.html
上一篇:找不到名稱“T”打字稿
