Photo by Mathias P.R. Reding on Unsplash
배열로 모든 타입을 받고 배열의 첫번째 요소를 리턴하는 함수
를 작성한다 가정
아무타입을 받고 아무타입이나 리턴하는 함수
-> any?
type SuperPrintAny = (a:any[]) => any
const superPrintAny: SuperPrintAny = (a) => a[0]
const anyA = superPrintAny([1,2,3,4])
anyA.toUpperCase() // anyA는 number기 때문에 런타임 오류 발생
anyA.toUpperCase()는 오류가 발생하는 코드임에도 불구하고 아무 경고도 해주지 않는걸 볼 수 있음
type SuperPrint = <T>(a:T[]) => T
const superPrint: SuperPrint = (a) => a[0]
const a = superPrint([1,2,3,4])
a.toUpperCase()
a는 숫자이기때문에 오류가 발생할 것이라고 코드가 실행되기전에 TS에서 경고해줌
generic은 사용자가 요구한대로 call signature를 생성해주는 도구
type SuperPrint = <T,M>(a:T[], b:M) => T
const superPrint: SuperPrint = (a) => a[0]
const a = superPrint([1,2,3,4],"x")
const d = superPrint([1,"ab",true,"123"],[])
TS는 generic을 처음 인식했을때와 generic의 순서를 기반으로 generic의 타입을 알게 됌
<T,M> <- generic의 이름을 설정해주는 단계
(a: T[], b:M ) <- generic이 사용되는 곳을 알려주는 단계 -> T는 함수의 첫번째 파라미터로 올 것이다. 두번째는 M이 올것이다 -> 파라미터로 들어오는 값을 인식 -> 파라미터로 ([1,2,3,4],"x")가 들어올때 첫번째 파라미터 [1,2,3,4]의 경우 숫자, 두번째 파라미터 "x"의 경우 문자열로 인식
이 단계에서 TS가 call signature를 작성
any와는 작동방식이 다름 -> 개발자가 요구하는대로 call signature를 생성한다는 뜻
generic의 call signature - 같은 함수라도 다른 call signature 생성해줌