call signatures
오버로딩(overloading)
복습!
function add(a:number, b:number){
return a + b;
}
const add1 = (a:number, b:number) => a + b;
타입을 지정할 땐 콜론( : ) 뒤에 데이터 타입을 적는다.
type Add = (a:number, b:number) => number;
const add:Add = (a, b) => a + b;
또는
type Add = {
(a: number, b: number) : number
}
const add:Add = (a, b) => a + b;
이런 방법도 있다~
이런 방법이 존재하는 이유는 오버로딩 때문!
오버로딩은 함수가 서로 다른 여러 개의 call signatures를 가지고 있을 때 발생됨
실제로 많은 오버로딩된 함수를 직접 작성하진 않을 것
그 대신 외부 라이브러리를 사용할 때, 거기서 오버로딩을 많이 사용함!
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에서는 Router.push()라는 함수가 있는데, string값으로 ('/home')이라고 적을 수도 있고,
객체 형식으로 ({path: '/home', state: 1}) 보낼 수도 있음. 두 가지 모두 작동해야 함
type Config = {
path: string,
state: object
}
type Push = {
(path: string) : void
(config: Config) : void
}
const push:Push = (config) => {
if(typeof config === 'string'){
console.log(config)
} else {
console.log(config.path, config.state)
}
}
type Add = {
(a: number, b: number) : number,
(a: number, b: number, c?: number) : number
}
const add:Add = (a,b,c?:number) => {
if(c) return a + b + c;
return a + b;
}
add(1, 2)
add(1, 2, 3)