8장 타입스크립트로 마이그레이션

ClassBinu·2024년 4월 28일

58 모던 JS 변환

tsc는 js -> ts 변환 컴파일러말고 구js -> 신js로 트랜스파일링하는 기능도 있음.
이렇게 모던 JS로 바꾸고 기능을 추가하는 것부터 시작할 수 있음.

for-of

for-in 문법은 사용 지양
(for-of, forEach 사용)

  • 객체 자신 뿐만 아니라 프로토타입 체이닝으로 상속 받은 열거 속성도 순회함.
  • 배열은 인덱스 외에도 내부의 객체 자체도 순회함.
  • 배열을 for-in 으로 순회하면 값이 아니라 인덱스(키)를 순회함.
const array: any = [3, 5, 7];
array.foo = "hello";

for (const i of array) {
  console.log(i); // 3, 5, 7
}

for (const i in array) {
  console.log(i); // 0, 1, 2, foo
}

단축 객체 표현 & 객체 구조 분해

연관 배열

키와 값으로 연결되어 있는 데이터 구조
JS에서는 Object(객체)
ES6에서는 Map 객체

단축 객체 표현(Enhanced Object Literals)

프로퍼티 이름과 변수 이름이 같을 때, 변수 값을 객체의 프로퍼티로 빠르게 설정

const name = "John";
const age = 30;

// 전통적인 객체 리터럴 방식
const person = {
    name: name,
    age: age,
    greet: function() {
        return `Hello, my name is ${this.name}`;
    }
};

// 단축 객체 표현 사용
const personShort = {
    name,
    age,
    greet() {
        return `Hello, my name is ${this.name}`;
    }
};

console.log(personShort.greet()); // "Hello, my name is John"

객체 구조 분해(Object Destructuring)

객체 속성을 개별 변수로 쉽게 추출

const person = {
    name: "Alice",
    age: 25,
    job: {
        title: "Developer",
        company: "Tech Co"
    }
};

// 객체 구조 분해 사용
const { name, age, job: { title, company } } = person;
console.log(name); // "Alice"
console.log(title); // "Developer"

// 함수 매개변수에서 구조 분해 사용
function introduce({ name, age }) {
    return `I'm ${name} and I am ${age} years old.`;
}

console.log(introduce(person)); // "I'm Alice and I am 25 years old."

TS에서는 'use strict' 필요 없음

엄격 모드모다 TS가 더 엄격함.
대신 alwaysStrict 설정 사용해야 함.

표준화 3단계 이상 기능

https://github.com/tc39/proposals

59 @ts-check, JSDoc

굳이..?

60 allowJS

TS와 JS 동시 사용

0개의 댓글