https://nomadcoders.co/typescript-for-beginners/lobby
함수를 호버했을 때 나타나는 것으로 함수를 어떻게 호출하고 반환해야 하는지를 알려줍니다. 즉, 함수 호출과 반환의 타입을 명시한 것입니다.
type Add = (a:number, b:number) => number;
const add : Add = (a, b) => a + b
Call Signatures를 통해 타입을 만들 수 있고 어떻게 함수가 작동되는지 서술해둘 수 있습니다.
Overloading이란 함수가 서로 다른 여러개의 call signatures를 가지고 있을 때 발생시킵니다.
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) //type이 string으로 뜹니다.
}else{
console.log(config.path) //or config.state를 넣을 수 있으며
//type은 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) // 가능
개수가 다른 상황에서는 옵셔널을 줌으로써 문제를 해결할 수 있습니다.
여러가지 다른 구조들이란 뜻으로 함수에서 같은 타입으로 리턴이 된다고 했을 때, '안녕'이라는 결과가 나오거나 '잘가'라는 결과가 나올 수도 있다는 것이죠
type SuperPrint = {
<T>(arr: T[]): T // 다음과 같이 generic type 선언
}
const superPrint: SuperPrint = (arr) => {
arr.forEach(i => console.log(i))
}
superPrint([1,2,3,4]) // 타입스크립트가 유추한 타입으로 만들어 줍니다.
superPrint([true, false, true])
superPrint(["a", "b", "c"])
concrete type vs generic type
concrete type은 number, boolean, string, void 등의 정해져 있는 타입이고 generic 타입은 placeholder 같은 개념입니다. generic으로 타입을 잡으면 선언되기 전까지는 어떤 타입인지 알 수 없습니다
generic type을 통해 확장도 해봅시다
type Player<E> = {
name: string
extraInfo: E
}
type MaxExtra = {
favFood: string
}
type MaxPlayer = Player<MaxExtra>
const max: MaxPlayer = {
name : "max",
extraInfo:{
favFood: "chicken"
}
}
const alice: Player<null> = {
name : "alice",
extraInfo: null
}