Knowee
Questions
Features
Study Tools

What is currying in TypeScript?

Question

What is currying in TypeScript?

🧐 Not the exact question you are looking for?Go ask a question

Solution

Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c). Currying doesn’t call a function. It just transforms it.

In TypeScript, currying can be implemented like this:

function curry(f: Function): Function {
  return function(a: any) {
    return function(b: any) {
      return f(a, b);
    };
  };
}

// usage
function sum(a: number, b: number): number {
  return a + b;
}

let curriedSum = curry(sum);

console.log( curriedSum(1)(2) ); // 3

In the above example, the curry function does the currying job. When we call curry(sum), it returns a function that keeps the passed argument in its lexical environment. When it gets called again, it takes the second argument and finally applies the original function to both.

This way, we can transform a function call with multiple arguments into a sequence of function calls with a single argument, which can be useful in various scenarios.

This problem has been solved

Similar Questions

Explain the following concepts! (9 points)a) Type declaration file (in TypeScript)b) Transpilerc) Static typing

Which of the following is not a type assertion in TypeScript?

Which of the following is not a type assertion in TypeScript?A. let myVar = <string>someValue;B. let myVar = someValue as string;C. let myVar: string = someValue;D. let myVar = (string)someValue;

Question: What will be the output of the following TypeScript code?class Person {  name: string;  age: number;  constructor(name: string, age: number) {    this.name = name;    this.age = age;  }  greet() {    console.log(Hello, my name is ${this.name} and I am ${this.age} years old.);  }}const john = new Person('John', 30);john.greet();*1 pointHello, my name is John and I am 30 years old.Hello, my name is undefined and I am undefined years old.Error: constructor not definedError: greet method not defined

The following TypeScript code has an error. Can you identify and correct it?class Animal { constructor(public name: string) {}}let dog = new Animal();console.log(dog.name);What is the error, and how would you correct it?

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.