#3 Functions

#3.0 Call Signatures

ν•¨μˆ˜ μœ„μ— 마우슀λ₯Ό μ˜¬λ Έμ„ λ•Œ λœ¨λŠ” ν•¨μˆ˜λ₯Ό μ–΄λ–»κ²Œ ν˜ΈμΆœν•΄μ•Ό ν•˜λŠ”μ§€, μ–΄λ–»κ²Œ λ°˜ν™˜λ˜λŠ”μ§€ μ•Œλ €μ£ΌλŠ” 정보λ₯Ό μ˜λ―Έν•œλ‹€. κ°œλ°œμžκ°€ νƒ€μž…μ„ μƒκ°ν•˜κ³  μž‘μ„±ν•  수 μžˆλ‹€λŠ” μž₯점이 μžˆλ‹€. μžλ°”μŠ€ν¬λ¦½νŠΈλ‘œ μ»΄νŒŒμΌλ˜μ§€ μ•Šκ³  νƒ€μž…μŠ€ν¬λ¦½νŠΈ ν™˜κ²½μ—μ„œλ§Œ μ‚¬μš©λ˜λŠ” μ½”λ“œμ΄λ‹€.

type Add = (a:number, b:number) => number

const add: Add = (a, b) => a + b

#3.1 Overloading

Function Overloading 은 μ™ΈλΆ€ λΌμ΄λΈŒλŸ¬λ¦¬μ— 자주 λ³΄μ΄λŠ” ν˜•νƒœλ‘œ, ν•˜λ‚˜μ˜ ν•¨μˆ˜κ°€ μ—¬λŸ¬ 개의 Call Signatureλ₯Ό κ°€μ§ˆ λ•Œ λ°œμƒν•œλ‹€.

type Add = {
    (a: number, b: number) : number,
    (a: number, b: string) : number
}

const add : Add = (a, b) => a + b // err => bκ°€ string일 경우 + κ°€ μ•ˆλ¨

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

μ—¬λŸ¬ 개의 argument 인 경우, λͺ¨λ“  λ³€μˆ˜λ₯Ό μ•ˆμ“Έ 수 도 μžˆλ‹€.

type Add = {
    (a: number, b: number) : number,
    (a: number, b: number, c: number) : number
}

const add : Add = (a, b, c) => { // err => c
    return a + b
}

const add : Add = (a, b, c?: number) => { // c => optional
    if(c) return a + b + c
    return a + b
}

#3.2 Polymorphism

λ‹€ν˜•μ„± - μ—¬λŸ¬ νƒ€μž…μ„ λ°›μ•„λ“€μž„μœΌλ‘œμ¨ μ—¬λŸ¬ ν˜•νƒœλ₯Ό κ°€μ§€λŠ” 것

type SuperPrint = {
    <T>(arr: T[]) => T // <---> : Generic
}

const superPrint: SuperPrint = (arr) => arr[0]

superPrint([1,2,3,4])
superPrint([true, false, true])
superPrint([1, 2, false, true, "hello"])
// μ—¬λŸ¬ νƒ€μž…μ΄ ν¬ν•¨λ˜μ–΄λ„ TSκ°€ 각 νƒ€μž…μ„ μΆ”λ‘ 

Concrete Type - number, string, void ...

Generic - νƒ€μž…μ˜ placeholder

#3.3 Generics Recap

=> Generic ... any와 λΉ„μŠ·ν•œλ°?!

=> no ! any μ‚¬μš©μ€ νƒ€μž… μ•ˆμ •μ„±μ„ 포기할 뿐 μ•„λ‹ˆλΌ 좜λ ₯κ°’μ˜ νƒ€μž…μ„ λ³΄ν˜Έν•  수 μ—†μŒ

μš”μ²­ν•œ μ œλ„€λ¦­ μˆœμ„œμ— 따라 λ§€κ°œλ³€μˆ˜μ— μ•Œμ•„μ„œ μ μš©ν•¨

type SuperPrint = <T, M>(a: T[], b: M) => T

const superPrint: SuperPrint = (arr) => arr[0]

superPrint([1,2,3,4], "x")
superPrint([true, false, true], 1)
superPrint([1, 2, false, true, "hello"], false)

#3.4 Conclusions

// μœ„μ™€ κ°™μŒ
function superPrint <T> (a: T[]) {
    return a[0]
}

μ œλ„ˆλ¦­μ€ μ»€μŠ€ν…€ 및 μž¬μ‚¬μš©μ΄ κ°€λŠ₯함

type Player<E> = {
    name: string
    extraInfo: E
}

type NicExtra = {
    favFood: string
}

type NicPlayer = Player<NicExtra>

const nic : NicPlayer = {
    name: "nico",
    extraInfo: {
        favFood: "Kimchi"
    }
}

const kim: Player<null> = {
    name: "Kim",
    extraInfo: null
}

μ œλ„ˆλ¦­μ€ λ‹€μ–‘ν•œ κ³³μ—μ„œ μ‚¬μš© κ°€λŠ₯함

useState<number>()

μ œλ„ˆλ¦­μ€ μ„ μ–Έ μ‹œμ μ΄ μ•„λ‹Œ, 생성 μ‹œμ μ— νƒ€μž…μ„ λͺ…μ‹œν•˜μ—¬ ν•˜λ‚˜μ˜ νƒ€μž…μ΄ μ•„λ‹Œ λ‹€μ–‘ν•œ νƒ€μž…μ„ μ‚¬μš©ν•  수 μžˆλ„λ‘ ν•˜λŠ” 기법이닀.

Last updated

Was this helpful?