#3.2 Polymorphism
Concrete type
- number, string, void, unknown...
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])
Generic type
- Generic type이란 type의 placeholder와 같은 개념
- call signature를 작성할 때, 확실한 타입을 모를때 함수가 추론하도록 사용
type SuperPrint = {
<T>(arr:T[]) : void
}
- return 값이 있는 함수
type SuperPrint = <T>(arr:T[]) => T
const superPrint : SuperPrint = (arr) => arr[0];
const a = superPrint(["hi", true, 30])
- 여러 arguments
type SuperPrint = <T, M>(a:T[], b:M) => T
const superPrint : SuperPrint = (arr) => arr[0];
const a = superPrint(["hi", true, 30], "lena");
- 함수의 generic 표현
function newFn<T>(a:T[]){
return a
}
- Obj 생성 시 {} generic 표현
type Player<E> = {
name: string,
extraInfo: E
}
const nico:Player<{}> = {
name: "Nico",
extraInfo: {
}
}
- Generic의 또 다른 표현식
type A = Array<number>;
let a:A = [1,2,3];
'공부 > TypeScript' 카테고리의 다른 글
타입스크립트 챌린지 (7) - 수동 설치하기 (0) | 2022.08.05 |
---|---|
타입스크립트 챌린지 (5) (0) | 2022.08.02 |
타입스크립트 챌린지 (3) (0) | 2022.06.29 |
타입스크립트 챌린지 (2) (0) | 2022.06.28 |
타입스크립트 챌린지 (1) - 오답노트 (0) | 2022.06.27 |