
: 타입스크립트에서는 함수의 매개변수와 반환값(return)의 타입을 명확히 지정할 수 있다.
function add(a: number, b: number): number {
return a + b;
}
a: number 와 b: number 는 타입이 지정된 매개변수이다.: number 는 반환 타입이다.: 함수의 매개변수를 선택적으로 만드려면 ?를 붙이면 된다.
function greet(name: string, age?:number): string {
return age ? `Hello, ${name}. You are ${age} years old.` : `Hello, ${name}.`
}
console.log(greet("Alice")); // Hello, Alice.
console.log(greet("Bob", 25)); // Hello, Bob. You are 25 years old.
age?: number → age는 있어도 되고 없어도 되는 선택적 매개변수?가 붙으면 undefined일 수도 있으니 주의해야 한다.: 매개변수에 기본값을 설정할 수도 있다.
function greet(name: string = "Guest"): string {
return `Hello, ${name}!`;
}
console.log(greet()); // Hello, Guest!
console.log(greet("Alice")); // Hello, Alice!
function logMessage(message: string): void {
console.log(message);
}
void는 아무것도 반환하지 않는 함수를 나타낸다.return;은 가능하지만 return 값;은 불가능하다.never 타입 (절대 반환되지 않는 함수)function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {
console.log("무한 루프");
}
}
never 타입은 절대 값을 반환하지 않는 함수에 사용된다.: 타입스크립트에서도 화살표를 사용할 수 있는데, 이 때 함수 표현식에 타입을 명시적으로 선언할 수 있다.
const multiply = (a: number, b: number): number => a * b;
console.log(multiply(2, 3)); // 6
let calculator: (x: number, y: number) => number;
calculator = (a, b) => a + b; // 가능
calculator = (a, b) => a * b; // 가능
calculator = (a, b) => `${a} + ${b}`; // ❌ 오류 발생 (반환 타입 불일치)
: 인터페이스를 사용해서 함수의 타입을 정의할 수도 있다.
interface MathOperation {
(a: number, b: number): number;
}
const add: MathOperation = (x, y) => x + y;
const subtract: MathOperation = (x, y) => x - y;
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
?)와 기본값을 활용하면 유연하게 함수를 정의할 수 있다.void, 절대 끝나지 않는 함수는 never를 사용한다.