Explain what is Cur...
Explain what is Cur...
Currying in TypeScript is a functional programming technique that transforms a function with multiple arguments into a sequence of functions, each taking a single argument. This approach allows each function to be called separately, one argument at a time, until all arguments have been provided and the final value is returned.
To understand currying in TypeScript, consider a function that takes multiple parameters. Normally, you would call this function by passing all the parameters at once. However, with currying, you transform this function so that it takes the first parameter and returns a new function that takes the second parameter, and so on, until all parameters are handled. This can be particularly useful for creating more modular and reusable code.
Here’s a basic example to illustrate how currying works in TypeScript:
function add(a: number): (b: number) => number {
return function(b: number): number {
return a + b;
};
}
const addFive = add(5);
const result = addFive(3); // result is 8
In this example, the add
function takes one number and returns another function that expects the second number. The addFive
function is a curried version of add
that always adds 5 to its argument.
In TypeScript, currying can also help with type safety by ensuring that each step of the function application is type-checked. This can prevent runtime errors and improve the overall robustness of the application.
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào