У меня есть методы внутри объекта, как показано ниже < /p>
const Api = {
person: {
find: (arg:{paramFind:string}) => {},
create: (arg:{paramCreate:string}) => {},
edit: (arg:{paramEdit:string}) => {},
remove: (arg:{paramRemove:string}) => {}
},
book: {
find: (arg:{paramFind:string}) => {},
create: (arg:{paramCreate:string}) => {},
edit: (arg:{paramEdit:string}) => {},
remove: (arg:{paramRemove:string}) => {}
}
} as const
< /code>
Мне нужно сделать функцию обертки, которая будет вызывать определенную функцию на основе ключей объекта и аргументов. Вот что я пробую до сих пор. < /P>
type TApi = typeof Api
function executeApi(arg:{
key: KEY,
method: METHOD,
param: Parameters[0]
}) {
// my other codes that will do cache stuff
// Line below is fine
return (Api[arg.key][arg.method] as any)(arg.param)
}
executeApi({
key:'person',
method: 'create',
param: {
paramCreate: 'John Doe'
}
})
< /code>
Ошибка в очереди < /p>
param: Parameters[0]
< /code>
Ошибка скажем < /p>
Type '{ readonly person: { readonly find: (arg: { paramFind: string; }) => void; readonly create: (arg: { paramCreate: string; }) => void; readonly edit: (arg: { paramEdit: string; }) => void; readonly remove: (arg: { paramRemove: string; }) => void; }; readonly book: { ...; }; }[KEY][METHOD]' does not satisfy the constraint '(...args: any) => any'.
Type '{ readonly person: { readonly find: (arg: { paramFind: string; }) => void; readonly create: (arg: { paramCreate: string; }) => void; readonly edit: (arg: { paramEdit: string; }) => void; readonly remove: (arg: { paramRemove: string; }) => void; }; readonly book: { ...; }; }[KEY][keyof { ...; }[KEY]]' is not assignable to type '(...args: any) => any'.
Type '{ readonly person: { readonly find: (arg: { paramFind: string; }) => void; readonly create: (arg: { paramCreate: string; }) => void; readonly edit: (arg: { paramEdit: string; }) => void; readonly remove: (arg: { paramRemove: string; }) => void; }; readonly book: { ...; }; }[KEY][string] | { ...; }[KEY][number] | { ....' is not assignable to type '(...args: any) => any'.
Type '{ readonly person: { readonly find: (arg: { paramFind: string; }) => void; readonly create: (arg: { paramCreate: string; }) => void; readonly edit: (arg: { paramEdit: string; }) => void; readonly remove: (arg: { paramRemove: string; }) => void; }; readonly book: { ...; }; }[KEY][string]' is not assignable to type '(...args: any) => any'.
< /code>
Мне нужно исправить это, поэтому он может принять параметр соответственно.
мне не волнует обратный тип этой функции. Я могу поднять другой вопрос для этого, если это необходимо. Просто нужно исправить при принятии параметров соответствующим образом < /p>
Что делать? Большое спасибо.
Playground
Подробнее здесь: https://stackoverflow.com/questions/797 ... ted-object