Functions
- call signature
- function의 type을 미리 지정해줄수있음
- type 지정과 function 지정을 분리시킬수있다.
- 만약 react.js 로 function을 짜고 props로 보내줄때, 이 call signature 을 보내줘야한다.
const Add = (a: number, b:number) => number
const add: ADD = (a, b) => { }
- Over loading
- 오버로딩은 함수가 여러개의 call signature 을 가질때 발생한다.
- polymorphism
- 여러가지 다른 구조들
- 여러 타입이 들어올 가능성을 열어둘수있음 —> Generic 을 받음
- Generic은 기본적으로 placeholder 을 사용해서 내가 사용한 코드를 기준으로 type을 바꿔줌.
- any 보다는 generic을 사용하길 권장
- → 만약 any 상태에서 toUpperCase() 를 하면 어떤 type이 들어와도 다 가능하지만, generic 이면 알아서 type을 유추해주기 때문에 더 안정성이 높다
- 타입스크립트가 타입을 유추할수있도록 해줌
type superPrint = {
(arr: number[]) : void
}
const SuperPrint: superPrint = (arr) => {
arr.map(i => console.log(i))
}
SuperPrint([1,2,3]) // 1, 2, 3
SuperPrint([1,2,"hello]) // error
--> 이런 함수에서 여러 인자의 type 을 받을 가능성을 열어두려면
-----------------------------------------------
type superPrint = {
<T>(arr: T[]) : T
}
const SuperPrint: superPrint = (arr) => {
arr.map(i => console.log(i))
}
SuperPrint([1,2,3]) // 1, 2, 3 (num type을 유추함)
SuperPrint(["first", "hene", "hello"]) // first, hene, hello (str type을 유추함)
function superPrint<T> = (a: T[]) => {
return a[0];
}