[TS] TS Doc Handbook 1회독 - 2
좁히기(Narrowing)
typeof 키워드를 사용한 타입 가드
TS 내부에서 !!로 true/false 값을 받는 경우 type은 boolean이 아닌 리터럴 타입이 된다.
// both of these result in 'true'
Boolean("hello"); // type: boolean, value: true
!!"world"; // type: true, value: true
Truthiness narrowing
null은 js의 오류로 인해 typeof 키워드를 사용하면 'object'입니다. 그렇기에 narrowing을 하기위해서는 truthy 검사를 사용합니다. 하지만 falsy한 값에는 ''(빈 문자열), 0, null, undefined, 0n, NaN이 있는데 잘못 사용하면 ''(빈 문자열)과 0 또한 조건문에 걸릴 수 있기 때문에 조심해야 한다.
equality narrowing
===, !== 비교 연산자를 통해 타입까지 비교해 narrowing을 할 수 있다.
==, !=을 사용해서도 가능한데 범위가 좀 더 넓어진다. 예를 들어, ===로 비교하는 경우 null과 undefined가 구분되는 반면 ==을 사용하는 경우 null과 undefined가 같은 취급을 받는다.
in 연산자 narrowing
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
return animal.swim();
}
return animal.fly();
}
instanceof narrowing
function logValue(x: Date | string) {
if (x instanceof Date) {
console.log(x.toUTCString());
} else {
console.log(x.toUpperCase());
}
}
ts에서 타입을 직접 지정해주지 않는 경우 타입 추론을 통해서 ts가 적절한 타입을 부여합니다. 해당 변수에 값을 할당하는 경우에는 선언되었을 때의 타입에 대해서 오류를 찾아준다.
using type predicates: 흠... 잘 모르겠네
assertion function
discriminated unions
interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
type Shape = Circle | Square;
유니언 타입을 사용했을 때 같은 프로퍼티의 경우 유니언 타입으로 인식된다.
never type
narrowing을 진행하다가 아무 가능성도 남지 않았을 때 ts는 never 타입을 사용한다.
exhaustiveness checking
type Shape = Circle | Square;
function getArea(shape: Shape) {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.sideLength ** 2;
default:
const _exhaustiveCheck: never = shape;
return _exhaustiveCheck;
}
}
참고
무료 사이트 모음 2021, 자라는 것을 잘하는 개발, 2025.02.06
https://www.typescriptlang.org/ko/docs/handbook/typescript-from-scratch.html, 2025.02.06
https://opentutorials.org/course/5080, 생활코딩, 2025.02.06