반응형
Call Signatures
함수의 arguments에 직접 타입을 작성하는 방식이 아니다.
// function add (a:number,b:number){
// return a+b
// }
// console.log(add(1,3))
type TNums=(a:number, b:number)=>number
// const add : TNums = function(a,b){
// return a+b
// }
// 위와 동일한 문장
const add : TNums=(a,b)=>a+b
console.log(add(1,3))
void가 도출된다면 함수 동작구문에 return이 제대로 되지 않은거니 확인을 해야한다.
OverLoading
function overloading / method overloading이라고 많은 사람들이 다양하게 부른다.
실제로 많은 오버로딩된 함수를 직접 작성하지 않을 것이다.
overloading은 함수가 서로 다른 여러 개의 call signatures를 가지고 있을 때 발생한다.
// ex 1
type TNums={
(a:number, b:number) : number
(a:number, b:string) : number
}
const add : TNums=(a,b)=>{
if(typeof b === 'string') return a
return a+b
}
console.log(add(1,3))
// ex 2
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{
config.path
}
}
// ex 3
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
}
PolymorPhism(다양성 / 다양한 형태)
타입스크립트에서 함수는 다른 2~3개의 parameter를 가질 수 있다. 또는 string이나 object를 첫버냬째 parameter로 가질수 있다.
type SuperPrint={
(arr:number[]):void
(arr:boolean[]):void
(arr:string[]):void
(arr:(number | boolean | string)[]):void
(arr:[number | boolean | string]):void
}
const sPring:SuperPrint=(arr)=>{
arr.forEach(i=>console.log(i))
}
const qwer = [1,2,3,4,5]
sPring(qwer)
sPring([true,true,false,false])
sPring(['a','b','c'])
sPring([1,true,'soso'])
concrete type (단일 속성) 이 아닌 generic type을 줄 수 있다 . generic이란 타입의 placeholder같은 것이다.
type SuperPrint={
<TPrint>(arr:TPrint):void
}
// 아래와 같은 경우도 많이 보게 될 것임.
// type SuperPrint={
// <T>(arr:T[]):T
// }
// type SuperPrint = <T>(a:T[]) => T
const sPring:SuperPrint=(arr)=>{
arr.forEach(i=>console.log(i))
}
const qwer = [1,2,3,4,5]
sPring(qwer)
sPring([true,true,false,false])
sPring(['a','b','c'])
sPring([1,true,'soso'])
Generic에 type 추가
type SuperPrint= <T,M>(arr:T[], b:M)=>T
const sPring:SuperPrint = (arr) => arr[0]a
const qwer = [1,2,3,4,5]
const a = sPring(qwer,"hoho")
const b = sPring([true,true,false,false],123)
const c = sPring(['a','b','c'],false)
const d = sPring([1,true,'soso'],c)
console.log(a)
console.log(b)
console.log(c)
console.log(d)
type Player<E>={
name:string
extra:E
}
type Extra = {favFd:string}
type HohoPlayer = Player<Extra>
const hoho :HohoPlayer={
name:'haha',
extra:{
favFd:'toto'
}
}
type ArrNumbers = Array<number>
let a : ArrNumbers = [1,2,3,4,5]
728x90