View
호출 시그니쳐 (Call Signatures)
call signatures란 함수 이름 위에 마우스를 올렸을 때 뜨는 파라미터 타입 정보와 리턴 타입 정보로
함수를 어떻게 호출해야 하는지와 반환 타입도 알려줌. 함수 인수에 타입을 넣고싶지 않을 때 사용
함수의 call signature 타입 만드는 법
type Add = (a:number, b:number) => number;
const add:Add = (a,b) => a+b;
const add:Add = (a,b) => {a+b}; //Error! Type 'void' is not assignable to type 'number'
오버로딩(over loading)
함수가 서로 다른 call signatures를 가지고 있을 때 발생함. 외부 패키지나, 라이브러리 사용시 많이 사용됨
오버로딩 예시1) 파라미터 타입이 다른 경우
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)}
else {
console.log(config.path, config.state)
}
}
오버로딩 예시2) 파라미터 개수가 다른 경우
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
}
- 다른 개수의 파라미터를 가지게 되면, 나머지 파라미터도 타입을 지정해줘야 함
c?: number c는 아마도 number일 것이다.
다형성(polymorphism)
type SuperPrint = {
(arr: number[]):void
(arr: boolean[]):void
(arr: string[]):void
}
const superPrint: SuperPrint = (arr){
arr.forEach(i => console.log(i));
}
superPrint([1,2,3,4])
superPrint([true, false, true])
superPrint(["a", "b", "c"])
기존의 존재하는 타입(String, boolean, number..)인 concrete type 대신 generic 타입을 받을 거라고 알려줄거임
generic이란?
타입의 placeholder 같은 것으로 concrete type을 사용하는 것 대신 쓸 수 있음
타입스크립트로 placeholder를 작성할 수 있고 그게 뭔지 추론해서 함수를 사용하는 것
generic을 사용하는 이유
call signature를 작성할 때, 여기 들어올 확실한 타입을 모를 때 generic을 사용
generic 사용법
타입스크립트에 generic을 사용하고 싶다고 알려줘야함 : <generic명칭>
type SuperPrint = {
<TypePlaceholder>(arr: TypePlaceholder[]):void
}
const superPrint: SuperPrint = (arr){
arr.forEach(i => console.log(i));
}
superPrint([1, 2, 3, 4])
superPrint([1, 2, true, false])
- generic을 여러개 선언할 수 있음
1) 제네릭을 사용할거라고 알려주고 이름을 작성함
2) 어디서 이 제네릭을 사용할건지 알려줘야함
type SuperPrint = <T,M>(a: T[], b: M) => T
const superPrint: SuperPrint = (a) => a[0]
superPrint([1,2,3,4], "x")
function superPrint<T>(a: T[]) {
return a[0]
}
const a = superPrint([1, 2, 3,4])
const b = superPrint<boolean>([true, false, true]); //직접 타입을 전달할 수도 있음
- 제네릭을 사용해 타입을 확장할 수 있음 -> 재사용 가능
type Player<E> = {
name: string
extraInfo: E
}
type NicoExtra = {
favFood: string
}
type NicoPlayer = Player<{ favFood: string }>
const nico: Player<{favFood: string}> = {
name: "nico"
extraInfo: {
favFood: "kimchi"
}
}
const lynn: Player<null> = {
name: "lynn",
extraInfo: null
}
728x90
'Frontend > Typescript' 카테고리의 다른 글
[Typescript] Typescript로 블록체인 만들기 #4 CLASSES AND INTERFACES (1) | 2023.07.03 |
---|---|
[Typescript] Typescript로 블록체인 만들기 #3 FUNCTIONS 과제 답안 (0) | 2023.06.30 |
[Typescript] Typescript로 블록체인 만들기 #2 OVERVIEW OF TYPESCRIPT (1) | 2023.06.27 |
reply