TypeScript Functions
call signatures
- 함수 위에 마우스를 올렸을 때 보게 되는 것
- 인자(arguments)의 타입, 함수의 반환 타입을 알려주는 것
- 함수의 타입을 설명하고, 코드를 구현
type Add = (a:number, b:number) => number;
const add:Add = (a, b) => a + b;
Overloading
- 함수가 서로 다른 여러개의 call signatures를 가지고 있을 때 발생
- 예시) type이 다른 경우
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
}
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
}
Polymorphism (다형성)
- poly: many, several, much, multi
- morphos, morphic: form(형태), structure(구조)
concrete type
- number, string, boolean
- void, unknown
type SuperPrint = {
(arr: number[]):void
(arr: boolean[]) :void
(arr: string[]) :void
}
const superPrint: SuperPrint = (arr) => {
arr.forEach(i => console.log(i))
}
superPrint([1, 2, 3, 4])
superPrint([true, false, false])
superPrint(['1', '2', '3'])
- 매번 알맞은 call signature 을 설정해야하기 때문에, 불편
generic type
- Type Placeholder
- call signature을 작성할 때, 들어올 확실한 type을 모를 때 사용
- 사용자가 요구하는 대로 signature를 생성해줄 수 있는 도구
type SuperPrint = {
<TypePlaceholder>(arr: TypePlaceholder[]):void
}
const superPrint: SuperPrint = (arr) => {
arr.forEach(i => console.log(i))
}
superPrint([1, 2, 3, 4])
superPrint([true, false, false])
type SuperPrint = <T,M>(a: T[], b:M) => T
const superPrint: SuperPrint = (a) = > a[0]
superPrint([1, 2, 3], "hello")
type Player<E> = {
name: string
extraInfo: E
}
type LooExtra = {
favFood:string
}
type LooPlayer = player<LooExtra>
const loo: LooPlayer = {
name: "loo",
extraInfo: {
favfood: 'kimchi'
}
}