TypeScript는 정적 타입을 지원하여 코드의 안정성과 가독성을 높이는 데 도움을 줍니다.
개발자가 특정 값의 타입을 단언할 때 사용.
const input = document.querySelector('input') as HTMLInputElement;
input.value = "Hello!";
값이 null 또는 undefined가 아님을 단언.
const button = document.querySelector('button')!;
button.addEventListener('click', () => {
console.log("Button clicked!");
});
TypeScript는 DOM의 존재 여부를 알 수 없으므로 개발자가 직접 단언해야 함.
DOM 요소 접근 시 런타임 에러를 방지하려면 조건문 또는 단언 사용
const element = document.querySelector('.my-element');
if (element) {
element.textContent = "Hello, TypeScript!";
}
클래스 내부 속성의 가시성을 제어.
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;
}
}
읽기만 가능한 속성을 정의.
속성 값을 생성자에서만 설정할 수 있음.
class User {
readonly id: number;
constructor(id: number) {
this.id = id;
}
}
const user = new User(1);
// user.id = 2; // 오류 발생
클래스 속성의 읽기와 쓰기를 제어.
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");
}
}
}
인터페이스를 사용해 클래스가 특정 구조를 구현하도록 강제.
interface Animal {
name: string;
sound(): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
sound() {
console.log("Bark!");
}
}
구현되지 않은 메서드를 포함할 수 있는 클래스.
상속받은 클래스가 추상 메서드를 반드시 구현해야 함.
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;
}
}
타입을 매개변수로 받아 다양한 타입에서 재사용 가능.
function identity<T>(value: T): T {
return value;
}
const num = identity<number>(42);
const str = identity<string>("Hello");
유니언 타입: 여러 타입을 가질 수 있음.
타입 내로잉: 조건문 등을 사용해 특정 타입으로 좁혀 처리.
function printValue(value: string | number) {
if (typeof value === "string") {
console.log(`String: ${value}`);
} else {
console.log(`Number: ${value}`);
}
}
공유 가능한 타입 선언을 정의.
주로 라이브러리와 함께 사용.
declare module "my-library" {
export function myFunction(value: string): void;
}