본문 바로가기
script/Typescript

Typescript call signatures, overloading

by devved 2023. 1. 8.
반응형

call signatures

// call signatures -> 함수위에 마우스를 올렸을 때 보게 되는...! 창
// 결국 TS 가 인식하고 있는 type을 보여주는 것
type Add = (a:number, b:number) => number;

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

// 화살표 함수는 자연스럽게 return 값이 number라는 것 인식해줌
const add2 = (a:number, b:number) => a+b
// call signatures 는 (a:number, b:number) => number

// 위에서 타입 먼저 지정해줘서 아래와 같이 간단하게 쓸 수 있음 
const add: Add = (a, b) => a + b; 
// const add: Add = (a, b) => {a + b}; 얘는 괄호때문에 return type이 void로 인식되으로 error 발생

 

overloading

// overloading
// 함수가 서로 다른 여러개의 call signature를 가지고 있을 때 발생시킴

// 좋은 예시는 아니지만 여러 call signature가 있는 오버로딩 대표예시
type Add = {
    (a: number, b: number) : number
    (a: number, b: string) : number
}

const add: Add  = (a,b) => {
    if (typeof b === "string") return a 
    return a + b
}

// 자주쓰게 되는 실사용 예시(next.js)
type Config = {
    path: string, 
    state : object
}

type Push = {
    (path:string): void
    (config: Config):void
}

const push: Push = (config) => { // config 는 string | object
    if (typeof config === "string") { console.log(config) } // string
    else { // object
        console.log(config.path, config.state);
    }   
}

// 파라미터 개수가 다를 경우 
type Minus = {
    (a: number, b: number ) : number
    (a : number, b: number, c: number) : number
}

const minus: Minus = (a, b, c?:number) => { // c 파라미터가 선택사항이라는 것을 알려줘야함
    if (c) return a - b - c
    return a - b;
}
반응형

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

TS setting  (0) 2023.01.10
Typescript 인터페이스  (0) 2023.01.09
typescript Classes(+abstract class, abstract method)  (0) 2023.01.08
Typescript polymorphism, generic  (0) 2023.01.08
Typescript의 Type 정의  (0) 2023.01.08