Typescript 3. Advanced Types

Alpha, Orderly·2023년 1월 6일
0

typescript & javascript

목록 보기
3/6
post-thumbnail

Intersection Type

여러 타입을 만족하는 하나의 타입을 만듭니다.

Admin & Employee를 통해 겹치는 property는 겹쳐지고 겹치지 않는것은 겹치지 않게 된다.

Type guard

Union Type이 패러미터로 들어온다던지의 상황에선 타입체크를 먼저 해줄 필요가 생긴다

그 경우에

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

와 같이 typeof 를 통한 타입체크를 할수도 있고

in 을 이용해 Object나 Class의 Key값의 여부를 확인할수도 있다

Ex. 'name' in Person

class Person {
	name: string;
}
// 해당함

class Person {
	이름: string;
}
// 해당하지 않음

혹은 자바스크립트 내 instanceof를 이용해 클래스에 속하는지 확인할수 있다.

p = new Person()
console.log(p instanceof Person) // true 

Discriminated Union

interface Type1 {
  type: 'Type1';
  data1: string;
}

interface Type2 {
  type: 'Type2';
  data2: string;
}

interface Type3 {
  type: 'Type3';
  data3: string;
}

type MyType = Type1 | Type2 | Type3;

function consumeType(type: MyType) {
  switch (type.type) {
    case 'Type1':
      console.log(type.data1);
      break;
    case 'Type2':
      console.log(type.data2);
      break;
    case 'Type3':
      console.log(type.data3);
      break;
    default:
      throw new Error('Unreceable');
  }
}

혹은 위와 같이 Literal type을 이용해 Type을 Unique하게 지정하고 Switch 문으로 작동을 제어할수도 있다.

Type casting

Type casting은 <>을 이용하거나 as로 작동한다.

const userInputElement = <HTMLInputElement>document.getElementById('user-input')!;
/* == */
const userInputElement = document.getElementById('user-input')! as HTMLInputElement;

Function Overloading

함수의 이름은 같으나 패러미터가 다른것을 구현하기 위해 사용한다.

함수의 패러미터들을 정해놓는 부분과 함수를 구현하는 부분으로 나뉘는데

구현부에서는 위에서 정해진 패러미터를 모두 받을수있도록 구현해야 한다.

// 숫자와 숫자
function add(a: number, b: number): number;

// 문자와 문자
function add(a: string, b: string): string;

// 문자와 숫자
function add(a: string, b: number): string;

// 숫자와 문자
function add(a: number, b: string): string;

// 구현, Type Guard를 통해 올바르게 실행되도록 함.
function add(a: string | number, b: string | number) {
  if (typeof a === 'string' || typeof b === 'string') {
    return a.toString() + b.toString();
  }
  return a + b;
}

이를 사용하는 이유는

같은 두 타입을 패러미터로 받는 함수에 대해 Union type으로만 구성을 하면

function example(arg1: string | number | boolean, arg2: string | number | boolean) { ... }

가 되는데, 함수단에서 이 경우 다른 두 타입으로도 함수를 호출할수 있게 된다.

이를 사전에 방지하고 반드시 같은 타입으로만 실행하도록 위에

function example(arg1: string, arg2: string);

와 같이 지정해줄수 있다.

만약 상단부 지정하는 부분의 패러미터 갯수가 다를 경우 제일 갯수가 적은것을 기준으로 하여

함수를 구현 하는 부분에서 오른쪽부터 패러미터를 옵셔널 처리하여 받지 않을수도 있다고 표시 해 줄 필요가 있다.

// 1개
function printConsole(a: number): void;
// 2개
function printConsole(a: string, b: number): void;
// 제일 작은 갯수인 1개만 받아도 실행 될수 있도록 두번째 패러미터는 옵셔널 표시 함.
function printConsole(a: any, b?: any): void {
  console.log(a, b);
}

Optional Chaning && Nullish Coalising

위 두 문법은 Swift나 Kotlin같은 최신 문법에 익숙하다면 자주 볼수 있다

const fetchedUserData = {
  id: 'u1',
  name: 'Max',
  job: { title: 'CEO', description: 'My own company' }
};

console.log(fetchedUserData?.job?.title);

const userInput = undefined;

const storedData = userInput ?? 'DEFAULT';

위 코드에서 fetchedUserData?.job?.title 부분을 보면 물음표가 있는데

이 물음표가 쳐 진 부분이 undefined이면 무조건 undefined를 리턴하도록 하는것이다.

이를 통해 에러가 발생하지 않고 스무스하게 넘어간다.

Nullish Coalising은 아래의 ?? 인데

userInput이 undefined일 경우 대신 'Default'가 storedData 변수에 대입된다.

즉, 일종의 기본값 역할을 해 줄수 있다.

profile
만능 컴덕후 겸 번지 팬

0개의 댓글