내가 보려고 적은 TypeScript 핵심 요약 2

Joey·2025년 1월 7일

TypeScript 정리

TypeScript는 정적 타입을 지원하여 코드의 안정성과 가독성을 높이는 데 도움을 줍니다.


주요 개념

타입 어설션(Type Assertion)

개발자가 특정 값의 타입을 단언할 때 사용.

const input = document.querySelector('input') as HTMLInputElement;
input.value = "Hello!";

익스클레메이션 마크(!)

값이 null 또는 undefined가 아님을 단언.

const button = document.querySelector('button')!;
button.addEventListener('click', () => {
  console.log("Button clicked!");
});

DOM 접근/조작에서 타입 단언 필요

TypeScript는 DOM의 존재 여부를 알 수 없으므로 개발자가 직접 단언해야 함.

DOM 요소 접근 시 런타임 에러를 방지하려면 조건문 또는 단언 사용

const element = document.querySelector('.my-element');
if (element) {
  element.textContent = "Hello, TypeScript!";
}

접근 제어자 (Access Modifiers)

클래스 내부 속성의 가시성을 제어.

public: 모든 곳에서 접근 가능 (기본값).
private: 클래스 내부에서만 접근 가능.
protected: 상속받은 클래스에서도 접근 가능.

class Person {
  public name: string; 
  private age: number; 
  protected address: string;

  constructor(name: string, age: number, address: string) {
    this.name = name;
    this.age = age;
    this.address = address;
  }
}

읽기전용(Readonly) 속성

읽기만 가능한 속성을 정의.
속성 값을 생성자에서만 설정할 수 있음.

class User {
  readonly id: number;

  constructor(id: number) {
    this.id = id;
  }
}
const user = new User(1);
// user.id = 2; // 오류 발생

Getter / Setter

클래스 속성의 읽기와 쓰기를 제어.

class Rectangle {
  private _width: number = 0;

  get width(): number {
    return this._width;
  }

  set width(value: number) {
    if (value > 0) {
      this._width = value;
    } else {
      throw new Error("Width must be positive");
    }
  }
}

인터페이스 구현 (Implements)

인터페이스를 사용해 클래스가 특정 구조를 구현하도록 강제.

interface Animal {
  name: string;
  sound(): void;
}

class Dog implements Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  sound() {
    console.log("Bark!");
  }
}

추상 클래스(Abstract Class)

구현되지 않은 메서드를 포함할 수 있는 클래스.
상속받은 클래스가 추상 메서드를 반드시 구현해야 함.

abstract class Shape {
  abstract area(): number;
  abstract perimeter(): number;
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

  area(): number {
    return Math.PI * this.radius * this.radius;
  }

  perimeter(): number {
    return 2 * Math.PI * this.radius;
  }
}

제네릭 (Generics)

타입을 매개변수로 받아 다양한 타입에서 재사용 가능.

function identity<T>(value: T): T {
  return value;
}

const num = identity<number>(42);
const str = identity<string>("Hello");

유니언 타입 및 타입 내로잉 (Union Type & Type Narrowing)

유니언 타입: 여러 타입을 가질 수 있음.
타입 내로잉: 조건문 등을 사용해 특정 타입으로 좁혀 처리.

function printValue(value: string | number) {
  if (typeof value === "string") {
    console.log(`String: ${value}`);
  } else {
    console.log(`Number: ${value}`);
  }
}

타입 선언 파일 (.d.ts)

공유 가능한 타입 선언을 정의.
주로 라이브러리와 함께 사용.

declare module "my-library" {
  export function myFunction(value: string): void;
}
profile
멋쟁이사자처럼 프론트엔드 부트캠프 12기

0개의 댓글