더보기에 있는 링크와 이어집니다.
스태틱&인스턴스
// 스테틱
class MyClass {
static staticProperty = "I belong to the class!";
static staticMethod() {
console.log("This is a static method.");
}
}
console.log(MyClass.staticProperty);
MyClass.staticMethod(); // 스테틱 메서드
// 인스턴스
class MyClass2 {
instanceProperty = "I belong to an instance!";
instanceMethod() {
console.log("This is an instance method.");
}
}
const instance = new MyClass2();
console.log(instance.instanceProperty);
instance.instanceMethod(); // 인스턴스 메서드
* 스테틱과 인스턴스의 차이
스테틱
- 클래스 자체에 속한다.
- 클래스 이름을 통해 직접 접근한다.
- 인스턴스와 연관이 없다.
인스턴스
- 클래스의 인스턴스를 통해 접근한다.
- 인스턴스마다 고유의 값을 얻을 수 있다.
하이브리드 타입
나의 객체가 여러 형태를 가질 수 있도록 정의
interface Counter {
(start: number): string; // 함수 시그니처
interval: number; // 속성
reset(): void; // 메서드
}
function getCounter(): Counter {
const counter = ((start: number) => `Count starts from ${start}`) as Counter;
counter.interval = 1000;
counter.reset = () => {
console.log("Counter reset!");
};
return counter;
}
const counter = getCounter();
console.log(counter(5)); // Count starts from 5
console.log(counter.interval); // 1000
counter.reset(); // Counter reset!
클래스 확장 인터페이스
클래스에서 상속한 필드와 메서드 타입을 인터페이스가 받아들여,
그 클래스의 구조를 기반으로 한 인터페이스를 정의할 수 있는 기능
class Animal1 {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log(`${this.name} makes a sound.`);
}
}
interface Pet extends Animal1 {
owner: string;
play(): void;
}
class Dog implements Pet {
name: string;
owner: string;
constructor(name: string, owner: string) {
this.name = name;
this.owner = owner;
}
makeSound(): void {
console.log(`${this.name} barks!`);
}
play(): void {
console.log(`${this.name} is playing with ${this.owner}.`);
}
}
// 사용 예시
const myDog = new Dog("Buddy", "Alice");
myDog.makeSound(); // Buddy barks!
myDog.play(); // Buddy is playing with Alice.'TS' 카테고리의 다른 글
| 함수(Function)[2] (0) | 2024.11.25 |
|---|---|
| 함수(Function)[1] (0) | 2024.11.20 |
| Interface (2) (0) | 2024.11.18 |
| Interface (1) (0) | 2024.11.15 |
| Interface (0) | 2024.11.08 |