TypeScript - Class types

꼬디바아 ㅣ 2024. 2. 27. 12:25

728x90

TypeScript 대표이미지

 

728x90

TypeScript에서 클래스(class)를 만들 때는 클래스의 속성(properties)과 메서드(methods)에 대한 타입을 명시하여 클래스를 더욱 강력하게 타입 지정할 수 있다.

 

🖥️ 클래스 타입 선언 및 생성자(Constructor)

class Person {
    // 속성 타입 명시
    name: string;
    age: number;

    // 생성자 메서드
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

 

위의 예제에서 'Person' 클래스는 'name'과 'age' 라는 두 개의 속성을 가지며, 생성자를 통해 초기화  된다.

 

🖥️ 메서드와 인스턴스 메서드의 사용

class Person {
    name: string;
    age: number;

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

    // 메서드 정의
    introduce(): string {
        return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
    }
}

// 클래스 인스턴스 생성
const person1 = new Person('John Doe', 25);

// 메서드 호출
const introduction = person1.introduce();
console.log(introduction);

 

위 코드에서 'Person' 클래스에 'introduce' 메스드가 추가되었다. 이 메서드는 문자열을 반환하며, 클래스의 인스턴스를 사용하여 호출할 수 있다.

 

🖥️ 상속과 추상 클래스

// 추상 클래스 정의
abstract class Animal {
    abstract makeSound(): void;
}

// Animal 클래스를 상속받는 Dog 클래스 정의
class Dog extends Animal {
    makeSound(): void {
        console.log('Woof! Woof!');
    }
}

// Dog 클래스의 인스턴스 생성
const dog = new Dog();

// makeSound 메서드 호출
dog.makeSound();

 

위 코드에서는 'Animal'은 추상 클래스로, 추상 메서드 'makeSound' 를 정의한다. 'Dog' 클래스는 'Animal'을 상속받아 'makeSound' 메서드를 구현한다.

728x90