함수와 타입
함수 타입
function func(a: number, b: number) {
return a + b;
}
const add = (a: number, b: number) => a + b;
function introduce(name = "rachel", age: number, tall?: number) {
console.log(`name: ${name}`);
console.log(`tall: ${tall}`);
}
introduce("rachel", 20, 168);
introduce("rechel", 20);
function getSum1(...rest: [number, number, number]) {
let sum = 0;
rest.forEach((it) => (sum += it));
return sum;
}
getSum1(1, 2, 3);
function getSum2(...rest: number[]) {
let sum = 0;
rest.forEach((it) => (sum += it));
return sum;
}
getSum2(1, 2, 3, 4, 5);
함수 타입 표현식과 호출 시그니쳐
type Operation = (a: number, b: number) => number;
const add: Operation = (a, b) => a + b;
const sub: Operation = (a, b) => a - b;
const multiply: Operation = (a, b) => a * b;
const divide: Operation = (a, b) => a / b;
type Operation2 = {
(a: number, b: number): number;
name: string;
};
const add2: Operation2 = (a, b) => a + b;
const sub2: Operation2 = (a, b) => a - b;
const multiply2: Operation2 = (a, b) => a * b;
const divide2: Operation2 = (a, b) => a / b;
함수 타입의 호환성
function func(a: number): void;
function func(a: number, b: number, c: number): void;
function func(a: number, b?: number, c?: number) {
if (typeof b === "number" && typeof c === "number") {
console.log(a + b + c);
} else {
console.log(a * 20);
}
}
func(1);
func(1, 2, 3);
함수 오버로딩
function func(a: number): void;
function func(a: number, b: number, c: number): void;
function func(a: number, b?: number, c?: number) {
if (typeof b === "number" && typeof c === "number") {
console.log(a + b + c);
} else {
console.log(a * 20);
}
}
func(1);
func(1, 2, 3);
사용자 정의 타입 가드
type Dog = {
name: string;
isBark: boolean;
};
type Cat = {
name: string;
isScratch: boolean;
};
type Animal = Dog | Cat;
function isDog(animal: Animal): animal is Dog {
return (animal as Dog).isBark !== undefined;
}
function isCat(animal: Animal): animal is Cat {
return (animal as Cat).isScratch !== undefined;
}
function warning(animal: Animal) {
if (isDog(animal)) {
animal;
} else if (isCat(animal)) {
animal;
}
}
[참고]
한 입 크기로 잘라먹는 타입스크립트