🔍 Narrowing

밑의 식은 왜 오류가 날까?

const 함수 = (x: number | string) => {
  console.log(x + 2);
};

함수(3);

타입스크립트는 엄격해야하기때문에, x 파라미터의 타입이 union type이라(number일수도, string일수도) 확실하게 지정해주지 않아서 오류가 나는것이다.

그렇기 때문에 x의 타입이 string일때와 number일때의 조건식을 구분해서 콘솔창을 띄어달라는 조건식을 추가해야한다.

const 함수 = (x: number | string) => {
  if (typeof x === "string") {
    console.log("타입이 string 인", x);
  } else if (typeof x === "number") {
    console.log("타입이 number인", x);
  }
};
함수(3);

이런식으로 추가적인 타입체크를 이용해서 변수의 타입의 범위를 줄여주는 것을 Narrowing이라고 한다.

narrow는 좁은 이라는 뜻을 가지고 있다.

const 함수 = (x: number | string) => {
  const array: number[] = [];
  if (typeof x === "number") {
    array[0] = x;
  }
};

함수(1);

이런식으로 작성해도 에러가 나지는 않지만, if문으로 타입체크를 했을땐 else 나 else if문을 작성해주는것이 좋다.


🔍 Assertion

const 함수 = (x: number | string) => {
  const array: number[] = [];
  array[0] = x as number;
};

함수(1);

프로그래밍에서 assertion은 참, 거짓을 미리 가정하는 문이라고 한다.

위처럼 as를 사용해서 타입스크립트 컴파일러에게 이 변수를 number로 생각해달라고 말할 수 있다.

const 함수 = (x: number | string) => {
  const array: number[] = [];
  array[0] = x as number;
  console.log(typeof x); // string
};

함수("1");

하지만 as number라고 해놓고 '1'을 안에 넣어도 string으로 출력이 되는데,

as 타입은 해당 타입으로 타입변환을 시켜준다는 의미보다, 타입쉴드를 임시로 해제해준다는 의미이다.

as 키워드는 union type같이 복잡한 타입을 하나의 타입으로 줄여주는 역할을 하는 것이다.

그래서 as 문법은 어떤 타입이 올지 정확히 아는 상태에서 사용해야하고, 대부분은 narrowing 문법을 사용해서
타입을 체크한다.

profile
https://brgndy.me/ 로 옮기는 중입니다 :)

0개의 댓글

Powered by GraphCDN, the GraphQL CDN