1. 함수 타입 정의 기본 원칙
함수를 설명하는 가장 좋은 방법은 어떤 매개변수를 받고, 어떤 결과값을 반환하는지를 명확히.
function func(a: number, b: number) {
return a + b;
}
- `a`와 `b`는 `number` 타입의 매개변수
- 결과값도 `number` 타입
2. 화살표 함수의 타입 정의
화살표 함수에서도 동일하게 매개변수와 반환 타입을 정의할 수 있음.
const add = (a: number, b: number): number => a + b;
- `: number`를 반환 타입으로 지정
- 명시적으로 반환 타입을 설정하면 코드 가독성이 좋아짐
3. 함수의 매개변수
3.1 기본값 설정 (default parameter)
기본값을 설정하면, 함수 호출 시 값이 전달되지 않아도 기본값을 사용할 수 있음.
function introduce(name = "name", age: number, tall?: number) {
console.log(`name: ${name}`);
if (typeof tall === "number") {
console.log(`tall:${tall + 10}`);
}
}
introduce("peanut", 27, 175);
introduce("peanut", 27);
- `name`은 기본값` "name"`을 가짐
- `tall`은 선택적 매개변수 (`?` 표시) → 필수 매개변수 뒤에 위치해야 함!
- typeof tall === "number" 체크 후 값 활용 가능
❗ 주의: tall?: number와 tall: number | undefined는 다른 개념!
tall?: number → 선택적 매개변수 (생략 가능)
tall: number | undefined → 반드시 undefined를 포함해야 함
4. 가변 매개변수 (rest parameter)
여러 개의 인수를 받을 때는 rest (...)를 사용!
function getSum(...rest: number[]) {
let sum = 0;
rest.forEach((it) => (sum += it));
}
getSum(1, 2, 3); // 6
getSum(1, 2, 3, 4, 5); // 15
함수 타입 표현식
/**
* 함수 타입 표현식
*/
type Operation = (a: number, b: number) => number;
const ex: (a: number, b: number) => number = (a, b) => a + b;
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;
호출 시그니처 ( Call Signature )
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;
add2(1, 2);
add2.name;
'프로그래밍 언어 > TypeScript' 카테고리의 다른 글
[TypeScript] 함수 오버로딩과 타입 가드 (0) | 2025.02.26 |
---|---|
[TypeScript] 함수 타입의 호환성 (0) | 2025.02.25 |
[TypeScript] 서로소 유니온 타입 (0) | 2025.02.24 |
[TypeScript] 타입 단언, 좁히기 (0) | 2025.02.24 |
[TypeScript] 타입스크립트를 이해한다는 것은 뭘까? (0) | 2025.02.20 |