JavaScript
[TypeScript][노마드코더] #3 FUNCTIONS(2)
포시
2023. 1. 17. 19:48
728x90
다형성(Polymorphism)
poly: 많은, 다수의
morphos or morphic: form(형태), structure(구조) 즉, 형태나 구조, 모양
polymorphous: 여러가지 다른 형태, 구조, 모양들
Generic type
type SuperPrint = {
(arr: number[]): void
(arr: booleanp[): void
}
const suerPrint: SuperPrint = (arr) => {
arr.forEach(i => console.log(i))
}
superPrint([1, 2, 3, 4])
superPrint(true, false, true)
superPrint(["a", "b", "c"]
위의 코드에서 superPrint로 오게될 파라미터들에 대해 계속해서 type에 추가해줘야 하는 상황이 발생한다.
여기서 우리는 generic을 사용해 더 편해질 수 있다.
generic type은 placeholder와 비슷하다.
예시)
type SuperPrint = {
<T>(arr: T[]): void
}
const suerPrint: SuperPrint = (arr) => {
arr.forEach(i => console.log(i))
}
superPrint([1, 2, 3, 4])
superPrint(true, false, true)
superPrint(["a", "b", "c"]
superPrint([1, 2, true, false])
superPrint([1, 2, true, false, "hello"])
type SuperPrint = {
<T>(arr: T[]): T
}
const suerPrint: SuperPrint = (arr) => arr[0]
conat a = superPrint([1, 2, 3, 4])
conat b = superPrint([true, false, true])
conat c = superPrint(["a", "b", "c"]
conat d = superPrint([1, 2, true, false])
conat e = superPrint([1, 2, true, false, "hello"])
Generic을 통해 call signature를 직접 만들지 않아도 된다.
type SuperPrint = <T, M>(a: T[], b: M) => T
const suerPrint: SuperPrint = (a) => a[0]
conat a = superPrint([1, 2, 3, 4], "x")
conat b = superPrint([true, false, true], 1)
conat c = superPrint(["a", "b", "c"], false)
conat d = superPrint([1, 2, true, false, "hello"], [])
이처럼 Generic에 두 번째 인자를 사용할 수도 있다.
Conclusions
function superPrint<T>(a: T[]) {
return a[0]
}
conat a = superPrint([1, 2, 3, 4])
conat b = superPrint([true, false, true])
conat c = superPrint(["a", "b", "c"])
conat d = superPrint([1, 2, true, false, "hello"])
type Player<E> = {
name: string
extraInfo: E
}
const nico: Player<{ favFood: string }> = {
name: "nico",
extraInfo: {
favFood: "kimchi"
}
}
type Player<E> = {
name: string
extraInfo: E
}
type NicoPlayer = Player<{ favFood: string }>
const nico: NicoPlayer = {
name: "nico",
extraInfo: {
favFood: "kimchi"
}
}
type Player<E> = {
name: string
extraInfo: E
}
type NicoExtra = {
favFood: string
}
type NicoPlayer = Player<NicoExtra>
const nico: NicoPlayer = {
name: "nico",
extraInfo: {
favFood: "kimchi"
}
}
이런식으로 원하는대로 코드를 확장하는 것이 가능하다.
type Player<E> = {
name: string
extraInfo: E
}
type NicoExtra = {
favFood: string
}
type NicoPlayer = Player<NicoExtra>
const nico: NicoPlayer = {
name: "nico",
extraInfo: {
favFood: "kimchi"
}
}
const lynn: Player<null> = {
name: "lynn",
extraInfo: null
}
새로운 lynn을 만들어 Player type을 갖다 쓴 모습.
function printAllNumbers(arr: number[]) {}
function printAllNumbers(arr: Array<number>) {} // 둘 다 같은 코드
728x90