반응형
기본형
// 인자 각각에 타입, 리턴 값에 타입
function addNum(a: number, b: number): number {
return a + b;
}
화살표 함수
// 변수 greet에 할당 받는 name 값에 타입, 변수 greet 에 타입
const greet: (name: string) => string = (name) => `Hello, ${name}`;
예제
function runMore(distance: number): number {
return distance + 10;
}
console.log(runMore(10));
function eat(calories: number) {
console.log("I ate " + calories + " calories");
}
// void : return 하지 않음
function sleepIn(hours: number): void {
console.log("I slept " + hours + " hours");
}
출력해보자.
let ate = eat(100);
console.log(ate);
let slept = sleepIn(10);
console.log(slept);
실습
// 매개변수가 string 일 때만 길이 출력하는 함수
function showLength(input: string | number) {
if (typeof input === "string") {
console.log(`길이: ${input.length}`);
}
else {
console.log("문자열이 아닙니다.");
}
}반응형
'Front-End > TypeScript' 카테고리의 다른 글
| TypeScript #11 (객체 지향) (0) | 2025.07.03 |
|---|---|
| TypeScript #10 (함수 유효성 검사) (0) | 2025.07.02 |
| TypeScript #8 (클래스 실습) (2) | 2025.07.02 |
| TypeScript #7 (타입 연습 문제) (0) | 2025.07.02 |
| TypeScript #6 (예제로 보는 모듈 맛보기) (0) | 2025.07.01 |