乐闻世界logo
搜索文章和话题

How can you specify default types for generics in TypeScript?

1个答案

1

In TypeScript, we can specify a default type for generics when defining them. This approach enables using the default type when calling the generic without explicitly providing a concrete type, enhancing code flexibility and reusability.

Steps to Define and Use Default Generic Types:

  1. Specify Default Types When Defining Generics: For example, if we want a generic to default to number when not explicitly specified, we can define it as:

    typescript
    function identity<T = number>(arg: T): T { return arg; }
  2. Using Generic Functions: When calling this generic function, you can omit generic parameters, and TypeScript will automatically use the default number type:

    typescript
    let output = identity(); // Without arguments or type, default is number console.log(output); // Output type is inferred as number

    You can also pass generic parameters to override the default type:

    typescript
    let stringOutput = identity<string>("myString"); console.log(stringOutput); // Output: myString

Example Explanation:

Suppose we have a function that returns the first element of an array. This function works for arrays of any type, but if called without specifying the array type, it should default to handling number-typed arrays:

typescript
function getFirstElement<T = number>(arr: T[]): T | undefined { return arr[0]; } let numbers = getFirstElement([1, 2, 3]); // Defaults to number type let strings = getFirstElement<string>(["apple", "banana", "cherry"]); // Specified as string type console.log(numbers); // Output: 1 console.log(strings); // Output: apple

This approach ensures flexibility and type safety while keeping the code concise and maintainable.

Summary:

Using default types for generics makes TypeScript code more flexible and reusable. It reduces code duplication and allows omitting type parameters in most cases, leveraging the type inference mechanism more effectively. This is especially valuable when developing large applications and libraries, improving development efficiency and code quality.

2024年8月4日 22:52 回复

你的答案