하루 기록

[모던 리액트] 01장, 필수 자바스크립트, 타입스크립트 본문

Book/모던 리액트 Deep Dive

[모던 리액트] 01장, 필수 자바스크립트, 타입스크립트

떼굴펜 2024. 5. 31. 11:03

필수 자바스크립트

구조분해할당

배열 구조 분해 할당

const array = [1, 2, 3, 4];
 
const [a, , , b] = array;                     // a=1, b=4
const [c, ...rest] = array;                  // c=1, rest=[2, 3, 4] 
const [d, e=10, , , f =20] = array;    // d=1, e=2, f=20

 

객체 구조 분해 할당

const obj = { a: 1, b: 2, c: 3 };

const {a, rest} = obj;                       // a=1, rest={b:2, c:3}
const {a: first, b : num} = obj;         // first=1, num=2
const {a=10, d=10} = obj;              // a=1, d=10 

 

 

타입스크립트 활용법

any 대신 unknown을 사용하자

function doSomething1(callback : any) {
    callback();
}

function doSomething2(callback : unknown) {
    callback();
}

doSomething1(100);       // 런타임 시 에러 발생
doSomething2(100);       // 'callback' is of type 'unkwon'

 

 

타입 가드를 적극 활용하자

instanceof, typeof

async function fetchSomething() {
  try {
     const response = await fetch('/api/something');
     return await response.json();
  } catch (e) {
     if (e instanceof UnAuthorizedError) {
        // do something
      }
      throw e;
  }
}

 

- in : 객체에 key가 존재하는지 확인

interface Student {
    age : number;
    score : number;
}
interface Teacher {
    name : string;
}


function doSomething (person : Student | Teacher) {
    if ('name' in person) {
       console.log(`내 이름은 ${person.name}이야`);
    }
}


제네릭

// 제네릭 사용 전
function getFirstAndLast(list : unknown[]) {
  return [list.at(0), list.at(-1)];
}
const [first, last] getFirstAndLast([1,2,3,4,5]); 
first     // unknown

// 제네릭 사용 후
function getFirstAndLast<T>(list : T[]) : [T, T] {
  return [list.at(0), list.at(-1)];
}
const [first, last] getFirstAndLast([1,2,3,4,5]); 
first    // number

 

인덱스 시그니처

: 객체의 key를 정의하는 방식

 

방식 1. 인덱스 시그니처 사용하기

type Hello = {
   [key : string] : number
}
const hello : Hello = {
    hello: 1,
    hi: 2
}
hello['hi']; // 2

❗ 단, 인덱스 시그니처에 익숙하지 않다면, Object.keys(hello)를 사용할 때 에러를 만날 수 있다.

해결방법은 아래와 같이 해결할 수 있다.

   1) as로 타입 지정해주기 : ( Object.Keys(hello) as Array<keyof Hello>).map( .... )

   2) Object.keys 대신할 함수 만들기

 

 

방식 2. Record<Key, Value> 사용하기

type Hello = Record<'hello' | 'hi', number>;
const hello : Hello = {
    hello: 1,
    hi: 2
}
hello['hi']; // 2