type Add = (a: number, b: number) => number;
const add: Add = (a, b) => a + b;
함수가 여러개의 call signatures를 가지고 있을 때 발생
type Add = {
(a: number, b: number): number;
(a: number, b: string): number; //b = number|string
};
const add: Add = (a, b) => {
if (typeof b === 'string') return a;
return a + b;
};
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);
}
};
type Add = {
(a: number, b: number): number;
(a: number, b: number, c: number): number; //c는 option
};
const add: Add = (a, b, c?: number) => {
if (c) return a + b + c;
return a + b;
};
add(1, 2); //3
add(1, 2, 3); //6
type SuperPrint = <TypePlaceholder>(arr: TypePlaceholder[]) => TypePlaceholder;
type SuperPrint = {
<TypePlaceholder>(arr: TypePlaceholder[]): void; //
};
const superPrint: SuperPrint = (arr) => {
arr.forEach((i) => console.log(i));
};
superPrint([1, 2, 3, 4]);
superPrint([true, false]);
superPrint(['1']);
superPrint(['hi', 1, false]);
type SuperPrint = {
<TypePlaceholder>(arr: TypePlaceholder[]): TypePlaceholder;
};
const superPrint: SuperPrint = (arr) => arr[0];
const a = superPrint([1, 2, 3, 4]); //number
const b = superPrint([true, false]); //boolean
const c = superPrint(['1']); //string
const d = superPrint(['hi', 1, false]); //string|number|boolean
type SuperPrint = <T, M>(a: T[], b: M) => T;
const superPrint: SuperPrint = (arr) => arr[0];
const a = superPrint([1, 2, 3, 4], 'e'); //boolean, string
const c = superPrint(['1'], 2); //string, number
const d = superPrint(['hi', 1, false], true); //string|number|boolean, boolean
function superPrint<V>(a: V[]) {
return a[0];
}
const a = superPrint<number>([1, 2, 3, 4]); //이러한 방식도 있음
const c = superPrint(['1']);
const d = superPrint(['hi', 1, false]);
type Player<E> = {
name: string;
extraInfo: E;
};
const ys: Player<{ favFood: string }> = {
name: 'ys',
extraInfo: {
favFood: 'sushi',
},
};
type NicoPlayer = Player<{ favFood: string }>;
const nico: NicoPlayer = {
name: 'nico',
extraInfo: {
favFood: 'sushi',
},
};
type A = Array<number>;
let a: A = [1, 2, 3, 4];
function printAllNumbers(arr: Array<number>) {
return arr;
}
useState<number>();