#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?