▶ Polymorphism (다형성) : 함수는 다양한 형태를 갖고 있음 / 여러 형태의 인자를 가질 수 있음
type SuperPrint = {
//case1
(arr:number[]):void
(arr:boolean[]):void
...
// concrete type으로 type들을 추가하는 방식
// concrete type : number,oolean,string,void,unknown,...
}
type SuperPrint = {
//case2
<TypePlaceHolder>(arr:TypePlaceHolder[]):void
// <> 안에는 원하는 generic이름을 붙여주면됨
// generic type : TypeScript가 type을 추론하도록 하는 type
}
▶ Generic Type
CallSignature를 확인해보면 TypeScript가 Type을 추론해서 설정해줌
▶ Practice1
const superprint:SuperPrint = (arr) =>{
arr.forEach(i=>console.log(i))
}
superPrint([1,2,3,4])
superPrint([true,false,true,false])
superPrint([1,2,false,"a","b"])
// 정상적으로 시행
type SuperPrint = {
<TypePlaceHolder> (arr:TypePlaceHolder[]):TypePlaceHolder
}
const superPrint:SuperPrint = (arr) => arr[0]
const a = superPrint([1,2,3,4]) // a type : number
const a = superPrint([true,false,true,true]) // b type : boolean
const a = superPrint(["a","b",3,4]) // c type : string
▶ Practice2
type SuperPrint = <T,M>(a:T[],b:V) => T
const superPrint : SuperPrint = (a) =>a[0]
const a = superPrint([1,2,3,4],"x")
const b = superPrint([1,2,true,false],"boolean")
'Web_Study > TypeScript' 카테고리의 다른 글
TypeScript_7:Class (0) | 2022.06.07 |
---|---|
TypeScript_6:Generic_2 (0) | 2022.06.02 |
TypeScript_4:CallSignature & Overloading (0) | 2022.05.26 |
TypeScript_3:Types_2 (0) | 2022.05.25 |
TypeScript_2:Types (0) | 2022.05.22 |