Typescript 对于以函数为参数并返回与输入函数具有相同类型的函数,什么是合适的类型?
我正在编写一个函数,它接受一个函数作为参数,然后将返回作为输入的同一个函数的修改版本。(请注意,函数已更改为承诺) 我希望确保在将函数传递给Typescript 对于以函数为参数并返回与输入函数具有相同类型的函数,什么是合适的类型?,typescript,Typescript,我正在编写一个函数,它接受一个函数作为参数,然后将返回作为输入的同一个函数的修改版本。(请注意,函数已更改为承诺) 我希望确保在将函数传递给addLoggerToFunc函数后,不会丢失键入 const foo = async (baz: string, bar: number) => { // ... Do something } export const fooWithLogger = addLoggerToFunc(foo) // I expect fooWithLogger t
addLoggerToFunc
函数后,不会丢失键入
const foo = async (baz: string, bar: number) => {
// ... Do something
}
export const fooWithLogger = addLoggerToFunc(foo)
// I expect fooWithLogger to have the same typings as foo
我尝试的是:
const addLoggerToFunc = <T, G>(plainFunc: (...args: T[]) => Promise<G>): ((...args: T[]) => Promise<G>) => {
return async (...args: T[]) => {
console.log(`function ${plainFunc.name} has been called`);
return plainFunc(...args);
};
};
const addLoggerToFunc=(plainFunc:(…args:T[])=>Promise:((…args:T[])=>Promise=>{
返回异步(…参数:T[])=>{
log(`function${plainFunc.name}已被调用`);
返回plainFunc(…args);
};
};
但是现在fooWithLogger
有一种
const fooWithLogger:(…参数:(字符串|数字)[])=>Promise
而不是
constfoowithlogger=(baz:string,bar:number)=>Promise
constaddloggertofunc=(plainFunc:(…args:T)=>Promise):((…args:T)=>Promise)=>{
返回异步(…参数:T)=>{
log(`function${plainFunc.name}已被调用`);
返回plainFunc(…args);
};
};
const addLoggerToFunc = <T, G>(plainFunc: (...args: T[]) => Promise<G>): ((...args: T[]) => Promise<G>) => {
return async (...args: T[]) => {
console.log(`function ${plainFunc.name} has been called`);
return plainFunc(...args);
};
};
const addLoggerToFunc = <T extends any[], G>(plainFunc: (...args: T) => Promise<G>): ((...args: T) => Promise<G>) => {
return async (...args: T) => {
console.log(`function ${plainFunc.name} has been called`);
return plainFunc(...args);
};
};