TypeScript Function overloads, ? ,??

강정우·2023년 6월 14일
0

TypeScript

목록 보기
19/22
post-thumbnail

Function overloads

type Combinable = string | number;

function add(a:Combinable, b:Combinable) {
    if (typeof a === 'string' || typeof b === 'string') {
        return a.toString() + b.toString();
    }
    return a + b;
}

const result = add('헬창', '개발자');
result.split(' ');
  • 위 코드의 문제 무엇일까? 바로 사용자는 분면 string 끼리 합쳐서 string과 관련된 메서드를 사용하려 하지만 IDE는 이렇게 인식하고 있기 때문에 string일 수 있고 또 number일 수 있다.

  • 물론 as 키워드를 사용하면 해결되긴 한다. 하지만 add를 사용할 때마다 위 as 키워드를 작성해줘야하는데 function 설정 자체를 하는 방법은 없을까? =>

const result = add('헬창', '개발자') as string;

Function overloads 사용법

function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a:Combinable, b:Combinable) {
    if (typeof a === 'string' || typeof b === 'string') {
        return a.toString() + b.toString();
    }
    return a + b;
}

const result = add('헬창', '개발자')
result.split(' ');
  • 해당 함수 바로 위에 같은 이름으로 입력값을 때 각각의 type과 return 값일 때 type을 지정해주면 된다.

  • 그러면 아래 파란 글씨로 다른 overload된 함수를 알려주기도 한다.

optional chaining

const fetchedUserData = {
    id: 'u1',
    name: '정우',
    // job: {title: 'CEO', description: 'My onw company'}
};
console.log(fetchedUserData?.job.title);
  • http req를 하거나 특정 시점에 없을 수 있는 데이터에 계속 접근하여 run time error를 내지 않도록 도와주는 option 키워드이다.

nullish Coalescing "??"

  • 보통 http req 결과로 나온 값에 대해 null일 경우 default값을 설정하기위해 사용한다.
const userInput = '';
const storedData = userInput || 'Default'; 
  • 일때 userInput이 null, undefined, false로 취급받아 'Default'가 나오게 된다. 그렇다면 만약에 "" 를 그대로 사용하고 싶다면 어떻게 할까? => ?? 를 하용한 이 키워드는 오직 null, undefined일때만 적용한다.
profile
智(지)! 德(덕)! 體(체)!

0개의 댓글