[ts] 함수

Lee Tae-Sung·2022년 12월 24일
0

ts

목록 보기
3/7
post-thumbnail

1. 선택적 매개변수

function hello(name?: string) {
    return `hello, ${name}`;
}

console.log(hello())
  • 여러 매개변수를 쓸 때 주의점

=> 선택적 매개변수는 필수 매개변수 앞에 있으면 안된다.

앞뒤로 섞여도 소용 없음

=> 굳이 쓰겠다면 undefined을 통해 명시적으로 변수를 넣어주어야함

function hello(name: string | undefined, age: number) {
    return `${name}, ${age}`;
}

console.log(hello(undefined, 1))

2. default 매개변수 (js와 동일)

function hello2(name='태성') {
    return `hello, ${name}`;
}

console.log(hello())

=> 매개변수 안에 특정한 값을 넣어주기 때문에
=> 이를 통해서 타입을 제공해줄 수 있는듯

3. 전개구문

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax

function add(...nums: number[]) {
    return nums.reduce((result, num) => result + num, 0);
}

console.log(add(1, 2, 3));
console.log(add(1, 2, 3,4, 5, 6));

4. this 처리

interface User {
    name: string;
}

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

function showName(this: User, age:number) {
    console.log(this.name, age);
}

const a = showName.bind(Sam);
a(1);

=> 앞의 this가 있더라도 뒤에 전달된 매개변수가 있다면 그것들부터 인식 시작.

5. Function Overloading

https://www.tutorialsteacher.com/typescript/function-overloading

=> 함수 안에서는 분명히 type에 따라 분기처리가 되어있는데
=> ts는 주어진 타입을 체크하기 때문에
=> return 값이 User(Object)일지 String 일지 확신할 수 없게 됨

interface User {
    name: string;
    age: number;
}
function join(name: string, age: number): User;
function join(name: string, age: string): string;
function join(name: string, age: number | string): User | string {
    if (typeof age === "number") {
        return {
            name,
            age,
        };
    } else {
        return '나이는 숫자로 입력';
    }
}

// console.log(join('ts', 1));
// console.log(join('ts', 'dd'));

const sam: User = join("Sam", 30);
const jane: String = join("Jane", "30");
profile
긍정적인 에너지를 가진 개발자, 이태성입니다.

0개의 댓글