Type Guard

νƒ€μž… κ°€λ“œλž€ νƒ€μž… μŠ€ν¬λ¦½νŠΈμ—μ„œ λ³€μˆ˜μ˜ νƒ€μž…μ„ 보닀 ꡬ체적으둜 μ’ν˜€ μ½”λ“œ μ•ˆμ •μ„±μ„ 높이기 μœ„ν•΄ μ‚¬μš©λ˜λŠ” ν‚€μ›Œλ“œμ΄λ‹€.

μš°λ¦¬κ°€ νƒ€μž… 슀크립트λ₯Ό μ‚¬μš©ν•˜λŠ” μ΄μœ λŠ” λ³€μˆ˜μ˜ νƒ€μž…μ„ μ—„κ²©ν•˜κ²Œ ν™•μΈν•˜μ—¬ λ°œμƒ κ°€λŠ₯성이 μžˆλŠ” μ—¬λŸ¬ μ—λŸ¬ 듀을 λŸ°νƒ€μž„μ΄ μ•„λ‹Œ 컴파일 νƒ€μž„μ— μž‘μ•„λ‚΄κΈ° μœ„ν•΄μ„œ 이닀. μ‰½κ²Œ 말해 νƒ€μž… μŠ€ν¬λ¦½νŠΈκ°€ λ³€μˆ˜μ˜ νƒ€μž… 좔둠을 더 μ›ν™œν•˜κ²Œ ν•˜κΈ° μœ„ν•΄ μ‚¬μš©λ˜λŠ” 것이닀.

κ°„λ‹¨ν•œ μ˜ˆμ‹œλ₯Ό λ“€μ–΄λ³΄μž.

fuction SampleFn (data: number | string) : void {
    console.log(data + 1);
}

μœ„μ˜ μ˜ˆμ‹œ μ½”λ“œλ₯Ό μ‹€ν–‰ν•˜λ©΄ ν•¨μˆ˜μ˜ λ§€κ°œλ³€μˆ˜κ°€ number νƒ€μž…μΈμ§€ stringνƒ€μž…μΈμ§€ ν™•μ‹€ν•˜μ§€ μ•Šμ€λ° λ§€κ°œλ³€μˆ˜ + 1을 μ‹€ν–‰ν•˜λ €κ³  ν•˜κΈ° λ•Œλ¬Έμ— μ—λŸ¬κ°€ λ°œμƒν•œλ‹€. 이런 경우, λ§€κ°œλ³€μˆ˜μ˜ νƒ€μž…μ— 따라 처리λ₯Ό λΆ„κΈ° ν•  수 μžˆλ„λ‘ νƒ€μž… κ°€λ“œλ₯Ό μ‚¬μš©ν•œλ‹€.

주둜 typeof, instanceof, in 3 κ°€μ§€ 연산듀이 μ‚¬μš©λœλ‹€.

typeof

λ¨Όμ € typeof μ—°μ‚°μžλŠ” μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œλ„ μ‚¬μš©μ΄ κ°€λŠ₯ν•˜λ©°, 이름 κ·ΈλŒ€λ‘œ λ³€μˆ˜μ˜ νƒ€μž…μ„ λ°˜ν™˜ν•œλ‹€.

const v1 = typeof "first";
const v2 = typeof 2;
const v3 = typeof true;
const v4 = typeof { age : 10};

console.log(v1, v2, v3, v4) // string number boolean object

λ•Œλ¬Έμ— ν™•μΈν•˜κ³ μž ν•˜λŠ” λ³€μˆ˜μ˜ νƒ€μž…μ„ 직관적이고 κ°„λ‹¨ν•˜κ²Œ νŒŒμ•…ν•˜μ—¬ μ½”λ“œλ₯Ό μž‘μ„±ν•  수 μžˆλ‹€.

typeof λ₯Ό μ‚¬μš©ν•΄ μœ„μ˜ 예제 μ½”λ“œλ₯Ό 바꿔보면

function SampleFn (data: number | string){
    if (typeof data === "string") console.log(`${data} + 1`)
    else console.log(data + 1)
}

μ΄λ ‡κ²Œ 각 νƒ€μž… λ³„λ‘œ λΆ„κΈ° 처리λ₯Ό ν•΄ λ‹€λ₯Έ 좜λ ₯ κ²°κ³Όκ°€ λ‚˜μ˜€κ²Œλ” ν•  수 μžˆλ‹€.

typeof μ—°μ‚°μžλ‘œ λ°˜ν™˜λ˜λŠ” νƒ€μž…λ“€μ€ μ•„λž˜μ™€ κ°™λ‹€.

string, number, bigint, boolean, symbol, undefined, object, function

in

in μ—°μ‚°μžλ„ typeof와 λ§ˆμ°¬κ°€μ§€λ‘œ μžλ°”μŠ€ν¬λ¦½νŠΈμ— μ‘΄μž¬ν•œλ‹€. λ³€μˆ˜κ°€ νŠΉμ • 속성을 κ°€μ§€κ³  μžˆλŠ”μ§€ ν™•μΈν•˜μ—¬ boolean 값을 λ°˜ν™˜ν•œλ‹€.

interface User {
    name: string;
    age: number;
    address?: string;
}

const user1: User = {
    name: 'aug',
    age: 20,
};

const user2: User = {
    name: 'kuku',
    age: 25,
    address: 'μ„œμšΈμ‹œ',
};

function hasAddress(user: User): boolean {
    return 'address' in user;
}

console.log(hasAddress(user1)); // false
console.log(hasAddress(user2)); // true

User μΈν„°νŽ˜μ΄μŠ€μ— μ˜΅μ…”λ„ ν”„λ‘œνΌν‹°μΈ addressλ₯Ό μƒμ„±ν•˜μ—¬ ν•΄λ‹Ή ν”„λ‘œνΌν‹°λ₯Ό κ°€μ§€λŠ” 객체, κ°€μ§€μ§€ μ•ŠλŠ” 객체λ₯Ό μƒμ„±ν–ˆλ‹€. in μ—°μ‚°μžλ₯Ό 톡해 ν•΄λ‹Ή ν”„λ‘œνΌν‹°λ₯Ό κ°€μ§€κ³  μžˆλŠ”μ§€ ν™•μΈν•˜λŠ” μ½”λ“œμ΄λ‹€.

instanceof

instanceof μ—°μ‚°μžλŠ” ν™•μΈν•˜λŠ” λ³€μˆ˜κ°€ μ–΄λ–€ ν΄λž˜μŠ€μΈμ§€, μ–΄λ–€ 클래슀λ₯Ό 상속 λ°›μ•˜λŠ”μ§€ ν™•μΈν•˜λŠ” μ—°μ‚°μžμ΄λ‹€. 말이 살짝 μ–΄λ €μš°λ―€λ‘œ κ°„λ‹¨ν•œ μ˜ˆμ‹œ μ½”λ“œλ₯Ό 톡해 μ•Œμ•„λ³΄μž.

class User {
  name: string;

  constructor(name: string) {
    this.name = name;
  }
  introduction(): void {
    console.log(`Hi my name is ${this.name}`);
  }
}

class AdminUser extends User {
  constructor(name: string) {
    super(name);
  }
  introduction(): void {
    console.log(`Hi my name is ${this.name}, I am an administrator user.`);
  }
}

class GuestUser extends User {
  constructor(name: string) {
    super(name);
  }
  introduction(): void {
    console.log(`Hi my name is ${this.name}, I am an Guest User`);
  }
}

const user1 = new AdminUser("aug");
const user2 = new GuestUser("kuku");

console.log(user1 instanceof User); // true
console.log(user1 instanceof AdminUser); // true
console.log(user1 instanceof GuestUser); // false

console.log(user2 instanceof User); // true
console.log(user2 instanceof AdminUser); // false
console.log(user2 instanceof GuestUser); // true

μœ„ μ½”λ“œμ—μ„œ AdminUser ν΄λž˜μŠ€μ™€ GuestUser ν΄λž˜μŠ€λŠ” User 클래슀λ₯Ό μƒμ†λ°›λŠ”λ‹€. 각 클래슀의 μΈμŠ€ν„΄μŠ€μΈ user1κ³Ό user2λ₯Ό instanceof μ—°μ‚°μžλ‘œ 확인해보면 뿌리 클래슀인 User와 각 μΈμŠ€ν„΄μŠ€μ˜ λΆ€λͺ¨ ν΄λž˜μŠ€μ€ trueλ₯Ό λ°˜ν™˜ν•˜μ§€λ§Œ λ‹€λ₯Έ ν΄λž˜μŠ€λŠ” falseκ°€ λ‚˜μ˜€λŠ” 것을 확인 ν•  수 μžˆλ‹€.

ν•„μžλŠ” 주둜 try catch 문을 톡해 μ—λŸ¬λ₯Ό 핸듀링 ν•  λ•Œ instanceof μ—°μ‚°μžλ₯Ό μ‚¬μš©ν•œλ‹€.

import axios, { AxiosError } from 'axios';

class ApiError extends Error {
    constructor(message: string) {
        super(message);
        this.name = 'ApiError';
    }
}

async function fetchData() {
    try {
        const response = await axios.get(API_ENDPOINT);
        console.log('Data:', response.data);
    } catch (error) {
        if (error instanceof AxiosError) {
            // AxiosError νƒ€μž…μ˜ μ—λŸ¬μΈ 경우
            console.error(`AxiosError: ${error.message}`);
            throw new ApiError('Failed to fetch data from the API.');
        } else {
            // λ‹€λ₯Έ μ’…λ₯˜μ˜ μ—λŸ¬μΈ 경우
            console.error(`Unknown error: ${error}`);
            throw new ApiError('An unknown error occurred.');
        }
    }
}

Last updated