function add(a:number, b:number){
return a+b
}
const add = (a:number,b:number)=>a+b
TypeScript는 자동으로 return 값이 number임을 파악함
▶ CallSignature : 함수 위에 마우스를 올려두었을 때 위에 뜨는 정보를 의미
함수를 어떻게 호출해야하는지, 함수의 반환 타입이 무엇인지 파악가능
먼저 함수의 타입을 설정하고 코드를 구현함으로써 어떻게 작동하는지 미리 체계적으로 계획가능
▶ CallSignature 생성법
type Add = {
(a:number, b:number) : number
}
//callsignature 생성
type Add = (a:number, b:number) => number
//축약형
const add:Add =(a,b) => a+b
// 이와같이 타입을 추가적으로 작성할 필요X
▶ Overloading : 함수가 여러개의 CallSignature를 가지고 있을 때 발생
다른 사람이 작성한 외부 라이브러리를 사용할 때, 많이 사용함
//Case1
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
}
//Case2
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)
}
}
Router.push("/home")
Router.push({
path:"/home",
state:1
})
//위의 코드는 Next.js에서 사용되는 Router라는 문법(다른 페이지로 넘어갈 때 사용)
//상단 코드는 그냥 home page로 이동
//하단 코드는 state값을 가지고 home page로 이동
//이런식으로 overloading은 많이 사용되어짐
▶ 다른 여러개의 argument를 가지고 있을 때
type Add = {
(a:number, b:number):number,
(a:number, b:number, c:number):number
}
// callsignature의 파라미터 개수가 다름
// callsignature에서 Add를 부를 때 a와b만 부를 수도, c를 optional적으로 부를 수도 있는 상황
const add:Add(a,b,c?:number)=>{
if(c) return a+b+c
return a+b
}
// 조건으로 c가 optional임을 TypeScript가 파악할 수 있도록 설정
'Web_Study > TypeScript' 카테고리의 다른 글
TypeScript_6:Generic_2 (0) | 2022.06.02 |
---|---|
TypeScript_5:Polymorphism & Generic (0) | 2022.05.31 |
TypeScript_3:Types_2 (0) | 2022.05.25 |
TypeScript_2:Types (0) | 2022.05.22 |
TypeScript_1 : Why use TypeScript? (0) | 2022.05.22 |