Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 对于以函数为参数并返回与输入函数具有相同类型的函数,什么是合适的类型?_Typescript - Fatal编程技术网

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);
  };
};