Câu hỏi phỏng vấn Typescript
Câu hỏi

Explain what is Cur...

Câu trả lời

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.

Understanding Currying in TypeScript

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.

Example of Currying in TypeScript

Here’s a basic example to illustrate how currying works in TypeScript:

typescript Copy
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.

Benefits of Currying

  1. Partial Application: Currying allows you to create new functions by fixing some parameters ahead of time, which is known as partial application. This can lead to more flexible and reusable code.
  2. Code Readability: By breaking down functions into smaller, single-responsibility functions, currying can improve code readability and maintainability.
  3. Function Composition: Curried functions are easier to compose into new functions, allowing more complex operations to be built from simpler ones.

TypeScript Specifics

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.

Challenges and Consideratio...

senior

senior

Gợi ý câu hỏi phỏng vấn

senior

Why is the infer keyword needed in TypeScript?

middle

What is Mixin Class in TypeScript?

junior

How could you check null and undefined in TypeScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào