function add(num1: number, num2: number): void {
// return num1 + num2;
console.log(num1 + num2);
}

function isAdult(age: number): boolean {
return age > 19;
}

/*                옵셔널 파라미터 포함 함수            */
function hello(name?: string): string {
return `Hello, ${name || "world"}`;
}

const result = hello(); // 인자를 안넣을 경우 옵셔널 파라미터 설정
const result2 = hello("Sam");
const result3 = hello(1234); // 타입 에러

function hello2(age: number | undefined, name: string): string {
if (age !== undefined) {
return `Hello, ${name}, You are ${age}.`;
} else {
return `Hello, ${name}`;
}
}

console.log(hello2(30, "Sam"));
console.log(hello2(undefined, "Sam"));

/*               나머지 매개변수 타입 작성법          */
function add(...nums: number[]) {
return nums.reduce((result, num) => result + num, 0);
}

add(1, 2, 3); // 6
add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 55

this관련

interface User {
name: string;
}

const Sam: User = {name: "Sam"};

// this를 제일 앞에
function showName(this:User, age:number, gender:'m'|'f') {
console.log(this.name, age, gender);
}

const a = showName.bind(Sam);
a(30, 'm');

함수 오버로드

interface User {
name: string;
age: number;
}

// 함수 오버로드 사용
function join(name: string, age: string): string;
function join(name: string, age: number): User;
function join(name: string, age: number | string): User | string {
if (typeof age === "number" {
return {
name,
age,
}
} else {
return "나이는 숫자로 입력해주세요.";
}
}

// User를 반환하는지 string을 반환하는지 확신이 없으므로 함수 오버로드 사용
const sam: User = join("Sam", 30);
const jane: string = join("Jane", "30");

'Frontend > TypeScript' 카테고리의 다른 글

[TypeScript] 제네릭  (0) 2024.08.13
[TypeScript] 클래스  (0) 2024.08.13
[TypeScript] 리터럴, 유니온/교차 타입  (0) 2024.08.13
[TypeScript] 인터페이스  (0) 2024.08.13
[TypeScript] 기본형  (0) 2024.08.13
okojin