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_Functional Programming_Higher Order Functions - Fatal编程技术网

Typescript 更改第一个参数类型的增强器函数?

Typescript 更改第一个参数类型的增强器函数?,typescript,functional-programming,higher-order-functions,Typescript,Functional Programming,Higher Order Functions,下面是一个更高阶的logFunctionName函数,它通过记录函数名来增强say。增强的enhancedSay函数采用与原始say函数相同的参数 function say(msg: string | number) { console.log(msg) } function logFunctionName<T extends (...args: any[]) => any>(func: T): (...funcArgs: Parameters<T>) =&g

下面是一个更高阶的
logFunctionName
函数,它通过记录函数名来增强
say
。增强的
enhancedSay
函数采用与原始
say
函数相同的参数

function say(msg: string | number) {
  console.log(msg)
}

function logFunctionName<T extends (...args: any[]) => any>(func: T): (...funcArgs: Parameters<T>) => ReturnType<T> {
  return (...args: Parameters<T>): ReturnType<T> => {
    console.log(func.name)
    return func(...args);
  };
}

const enhancedSay = logFunctionName(say)("hello");

// const enhancedSay2 = messageLength(say)("hello");
// => 5
函数say(msg:string | number){
控制台日志(msg)
}
函数logFunctionName any>(func:T):(…funcArgs:Parameters)=>ReturnType{
return(…args:Parameters):ReturnType=>{
console.log(函数名)
返回函数(…参数);
};
}
const enhancedSay=logFunctionName(say)(“您好”);
//const enhancedSay2=消息长度(say)(“你好”);
// => 5
现在我陷入了一个问题

如何编写更高阶的
messageLength
函数,通过将传递给它的第一个参数从字符串转换为表示字符串长度的数字来增强
say
。增强的
enhancedSay2
函数获取一个字符串,而原始的
say
函数获取一个数字


编辑:这是一个简化的示例。我真正想做的是创建一个高阶函数,它接受一个字符串,将该字符串注入DOM,并将一个元素传递给增强的函数。

我不会在函数类型中使函数泛型,而是在其参数类型和返回类型中,这应该会给我们一些空间:

function say(msg: string | number) {
  console.log(msg)
}

function logFunctionName<T extends (...args: any[]) => any>(func: T): (...funcArgs: Parameters<T>) => ReturnType<T> {
  return (...args: Parameters<T>): ReturnType<T> => {
    console.log(func.name)
    return func(...args);
  };
}

const enhancedSay = logFunctionName(say)("hello");

// const enhancedSay2 = messageLength(say)("hello");
// => 5
function messageLength<P extends any[], R>(func: (len: number, ...args:T) => R): (msg: string, ...args: P) => R {
  return (msg, ...args) => {
    return func(msg.length, ...args);
  };
}
function messageLength(func:(len:number,…args:T)=>R):(msg:string,…args:P)=>R{
返回(消息,…参数)=>{
返回函数(msg.length,…args);
};
}

感谢您提供了看起来非常好的解决方案。非常欢迎在您的答案中对发生的事情进行解释。@user1283776您认为哪些部分需要更多解释?