함수의, 함수에 의한, 함수를 위한 타입스크립트 사용법에 대해 알아봅시다 😋
type Add = (a: number, b: number) => number
const add: Add = (a, b) => a + b;
함수가 서로 다른 여러개의 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) }
else {
console.log(config.path, confoig.state);
}
}
함수가 서로 다른 call signatures와 파라미터의 개수도 다를 경우.
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;
}
// 일반적인 Call Signature 생성
type SuperPrint = {
<T>(arr: T[]): T;
}
// 화살표 함수 사용하여 Call Signature 생성
type SuperPrint = <T>(a: T[]) => T
const superPrint: SuperPrint = (arr) => arr[0];
const a = superPrint([1]); // -> type: number
const b = superPrint([true]); // -> type: boolean
const c = superPrint(["a"]); // -> type: string
const d = superPrint([false]); // -> type: boolean
// 선언문을 통한 함수
function superPrint <T>(a: T[]) {
return a[0];
}
// 화살표 함수 사용
const superPrint = <T>(a: T[]) => {
return a[0];
};
// 타입의 재사용
type Player<E> = {
name: string;
extraInfo: E;
}
type Extra = {
favFood: string;
}
type KimPlayer = Player<Extra>
const kim: KimPlayer = {
name: 'kim',
extraInfo: {
favFood: 'kimchi'
}
}