ReasonJun

Typescript : Overloading 본문

Frontend/Typescript

Typescript : Overloading

ReasonJun 2023. 6. 10. 12:59
728x90

In TypeScript, function overloading refers to the ability to define multiple function signatures for the same function name. This allows a function to accept different sets of arguments or have different return types based on the provided function signature.

 

Function overloading enables you to provide different ways to call a function while maintaining type safety and clarity. It helps in creating more flexible and reusable functions that can handle various input scenarios.

 

To define function overloads in TypeScript, you can use the function keyword followed by the function name and multiple function signatures using the declare keyword. Each function signature represents a different way to call the function.

 

Here's an example of function overloading:

// function - overloading

// * 1) 
function add0 (a: string, b: string) {
    return a + b
}

function add9 (a: number, b: number) {
    return a + b
}

add0('hello', 'world~') // 'hello world'
add9(1, 2) // 3
add0('hello', 2) // error
add9('hello', 2) // error

// * 2)

function add8(a: string, b: string): string // Type Declaration
function add8(a: number, b: number): number // Type Declaration
function add8(a: any, b: any) { // Function implementation
    return a + b
}

add8('hello', 'world~') // 'hello world~'
add8(1, 2) // 3
add8('hello', 2) // error
add8(2, 'world~') // error

It's important to note that the implementation of the function follows the function signatures and provides a single unified implementation. This implementation is not part of the overloads and serves as the common behavior for all the overloads.

 

Function overloading in TypeScript provides compile-time type checking and allows for more expressive and flexible function definitions. It improves code readability and helps prevent potential runtime errors by enforcing type safety.

728x90

'Frontend > Typescript' 카테고리의 다른 글

Typescript : Generic  (0) 2023.06.10
Typescript : Class & Access Modifiers  (2) 2023.06.10
Typescript : Explicit this  (0) 2023.06.10
Typescript : Optional / Readonly Attribute in Interface  (0) 2023.06.10
Typescript : Interface  (0) 2023.06.10
Comments