๐ด Call Signatures

// ํจ์๋ฅผ ์์ฑํ ๋, argument์ ํ์
์ ์ง์ ํ๊ณ ,
// return ๊ฐ์ ์ ์ถ์ํค๋ ๋ฐฉ์์ ์ฌ์ฉํ์ผ๋
const add = (a: number, b: number) => a + b;
// ๋ฏธ๋ฆฌ ํ์
์ ์ง์ ํ๋ฉด
type Add = (a: number, b: number) => number;
// argument์ ์ง์ ํ์
์ ์ ์ด์ฃผ์ง ์์๋ ๋๋ค.
const add: Add = (a, b) => a + b;
๐ Overloading
โช ์ค๋ฒ๋ก๋ฉ์ ํจ์๊ฐ ์๋ก ๋ค๋ฅธ ์ฌ๋ฌ ๊ฐ์ 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
}
โช ์ค๋ฒ๋ก๋ฉ์ ํจํค์ง๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ๋์์ธํ ๋ ๋ง์ ์ฌ๋๋ค์ด ์ฌ์ฉํ๋ค.

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) // config: string
else console.log(config.path, config.state) // config: Config
}
โช ํ๋ผ๋ฏธํฐ์ ๊ฐฏ์๊ฐ ๋ค๋ฅผ ๋๋ ์ค๋ฒ๋ก๋ฉ์ด ์ ์ฉ๋๋ค.
โช ์ฃผ๋ก ๋ง์ง๋ง์ ์ ํ ์ถ๊ฐ ํ๋ผ๋ฏธํฐ๋ฅผ ์ต์ ์ผ๋ก ์ฌ์ฉํ ๋ ๋ฐ์ํ๋ค.

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)
๐ก Polymorphism (๋คํ์ฑ = ์ฌ๋ฌ ๊ฐ์ง ๋ค๋ฅธ ๊ตฌ์กฐ๋ค)

// โ ๏ธ ์ฌ๋ฌ ๊ฐ์ง ํ์
๋ค์ ์ฌ์ฉํ ๋๋ง๋ค ํ์
์ ์ง์ ํ๊ธฐ์๋ ๋นํจ์จ์ ์ด๋ค.
type SuperPring = {
(arr: number[]): void
(arr: boolean[]): void
(arr: string[]): void
}
// ๐ก ์ ๋ค๋ฆญ ํ์
์ ์ฌ์ฉํด์ค์ผ๋ก์จ ๋ชจ๋ concrete type์ ๋ฐ์ ์ ์๋ค.
type SuperPrint = {
<T>(arr: T[]): T
}
const superPring: SuperPrint = (a) => a[0]
// ๐ ํ๋ผ๋ฏธํฐ๋ก ๋ค์ด์จ ํ์
์ ์ ๋ค๋ฆญ์ด ๊ฐ์งํ์ฌ ๋ฐฐ์ด์ ํ์
์ผ๋ก ์ ์ฉํ๋ค.
const a = superPrint([1, 2, 3, 4])
// <number>(arr: number[]) => number
const b = superPrint([true, false, ture])
const c = superPrint(["a", "b", "c"])
const d = superPrint([1, 2, true, false, "hello"])

// ๋ ๊ฐ ์ด์์ ์ ๋ค๋ฆญ ํ์
์ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ
type SuperPrint = <T, M>(a: T[], b: M) => T
const superPrint: SuperPrint = (a) => a[0]
const a = superPrint([1, 2, 3, 4], "x")
const b = superPrint([ture, false, true], 1)
const c = superPrint(["a", "b", "c"], false)
const d = superPrint([1, 2, true, false, "hello"], [])
๐ข Conclusion

type Player<E> = {
name: string
extraInfo: E
}
type RyongExtra = {
favFood: string
}
type RyongPlayer = Player<RyongExtra>
const ryong: RyongPlayer = {
name: "ryong",
extraInfo: {
favFood: "kimchi"
}
}
const jeong: Player<null> = {
name: "jeong",
extraInfo: null
}
'TypeScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ TS ] Classes and Interfaces (0) | 2022.07.17 |
---|---|
[ TS ] What is TypeScript? (0) | 2022.07.08 |