728x90
반응형
- Polymorphism
배열의 요소를 하나씩 print하기
type SuperPrint = {
(arr: number[]):void
(arr: boolean[]):void
(arr: string[]):void
}
const superpring: SuperPring = (arr) => {
arr.forEach(i => console.log(i))
}
superPrint([1, 2, 3, 4])
superPrint([true, false, trune])
superPrint(["a", "b", "c"])
지금 세 개의 call signatures가 있다.
하지만 다 각 각 존재한다.
superPrint([1,2,true,false])
이 경우도 말이 안되는 것이 아니다. 그러므로 generic을 사용할 것이다. 타입의 placeholder같은 거라고 할 수 있다.
타입스크립트가 타입을 유추할 수 있게 하는 것이다!
먼저 argument가 generic을 받을 것이라는 것을 알려줘야 한다.
type SuperPrint = {
<TypePlaceholder>(arr: TypePlaceholder[]):void
}
const superpring: SuperPrint = (arr) => {
arr.forEach(i => console.log(i))
}
superPrint([1, 2, 3, 4])
superPrint([true, false, trune])
superPrint(["a", "b", "c"])
superPrint([1, 2, true, false])
이렇게 되면, 타입스크립트는 예상해서 유추한 call signature를 우리에게 보여주게 된다.
즉, 알아서 타입을 예상해서 작동한다.!!!
type SuperPrint = {
<T>(a: T[]): T
}
const superpring: SuperPrint = (arr) => arr[0]
const a = superPrint([1, 2, 3, 4])
const b = superPrint([true, false, trune])
const c = superPrint(["a", "b", "c"])
const d = superPrint([1, 2, true, false])
이렇게 하면 T로 더 간단하게 나타낼 수 있다.
그리고 각 각의 a는 number타입으로, b는 boolean으로 등으로 나타낼 수 있다.
***placeholder를 써야지 각 타입이라고 정해줄 수 있어서 코드가 보호받을 수 있다.
왜냐하면 지금 각 arr의 [0] 즉, 첫번째 타입으로 리턴하게 해두었기 때문에 d에서 에러가 날 수 있다.
- Generics Recap
여러개의 제네릭을 동시에 생성 가능하다.
type SuperPrint = <T,M>(a: T[], b:M) => T
const superpring: SuperPrint = (arr) => arr[0]
const a = superPrint([1, 2, 3, 4], "x")
const b = superPrint([true, false, trune],1)
const c = superPrint(["a", "b", "c"], false)
const d = superPrint([1, 2, true, false, "hello"], [])
타입스크립트는 제네릭을 처음 인식했을 때제네릭의 순서를 기반으로 제네릭의 타입을 인식한다.
즉, T는 첫번째 파라미터로 오고, M이 두번째 파라미터로 오는 것이다.
728x90
반응형
'내가 헷갈려서 정리하는 코딩 > Typescript' 카테고리의 다른 글
Call Signatures, Overloading (0) | 2023.06.01 |
---|