Implementing Function Overloading in TypeScript
Published on
December 26, 2024
Updated on
December 26, 2024
10
min read
TypeScript
In TypeScript, function overloading allows you to define multiple function signatures for a single function. With function overloading, you can support different parameters and return types under the same function name. Here, we will explore the use and best practices of function overloading in TypeScript through two examples.
Example 1: Implementing Function Overloading in a Class
export class BookService {
/**
* Get a book by ID
* @param id Book ID
* @returns A book
*/
getBook(id: string): Book;
/**
* Get books by condition
* @param condition Book condition
* @returns A list of books
*/
getBook(condition: { title?: string; publishTime?: Date }): Book[];
public getBook(condition: string | { title?: string; publishTime?: Date }): Book | Book[] {
if (typeof condition === 'string') {
// Logic to get a book by ID
return {} as Book;
}
// Logic to get books by condition
return [{} as Book];
}
}
Example 2: Using Function Overloading in a Regular Function
/**
* Get a book by ID
* @param id Book ID
* @returns A book
*/
export function getBook(id: string): Book;
/**
* Get books by condition
* @param condition Book condition
* @returns A list of books
*/
export function getBook(condition: { title?: string; publishTime?: Date }): Book[];
export function getBook(condition: string | { title?: string; publishTime?: Date }): Book | Book[] {
if (typeof condition === 'string') {
// Logic to get a book by ID
return {} as Book;
}
// Logic to get books by condition
return [{} as Book];
}
Summary
Function overloading in TypeScript is a powerful feature that helps handle different scenarios under the same purpose. Depending on your needs, you can implement function overloading in a class or choose a standalone function approach to better suit your project strategy.