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:
-
Specify Default Types When Defining Generics: For example, if we want a generic to default to
numberwhen not explicitly specified, we can define it as:typescriptfunction identity<T = number>(arg: T): T { return arg; } -
Using Generic Functions: When calling this generic function, you can omit generic parameters, and TypeScript will automatically use the default
numbertype:typescriptlet output = identity(); // Without arguments or type, default is number console.log(output); // Output type is inferred as numberYou can also pass generic parameters to override the default type:
typescriptlet 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:
typescriptfunction 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.