Front-End/TypeScript

타입스크립트 클래스 & 인터페이스

Voyage_dev 2024. 7. 24. 17:54

 

클래스

  • 객체를 어떤 필드(값)와 메서드(함수)로 표현하여 만들기 위한 설계
class Vehicle {
	drive(): void {
		console.log('run run');
	}
}

const vehicle = new Vehicle();
vehicle.drive(); // run run;

// 상속 (inheritance)
// 부모가 자식에게 부모 클래스의 필드나 메서드에 속성을 물려주는 개념
class Car extends Vehicle {
	// 자식 클래스에서 상속받은 메서드를 새롭게 재정의 할 수 있다 => 오버라이딩(overriding)
	drive(): void {
		console.log('car drive');
	}
}

const car = new Car();
car.drive(); // car drive

 

클래스 modifier

  • 메서드 앞에 키워드(modifier)에는 public, private, protected가 있다.
  • public : 언제 어디서나 호출이 가능하다.
  • private : 해당 클래스 안의 다른 메서드에서만 호출을 할 수 있다.
    • 어떤 클래스 안에서 메서드가 있는데 private으로 정의가 되어 있으면 인스턴스로 통해서 만들어진 객체에서는 참조할 수 없고 클래스 안에서만 쓸 수 있다.
  • protected : 해당 클래스 안의 다른 메서드 안에서만 호출 되거나, 자식 클래스의 다른 메서드에서 호출이 될 수 있다.
class Vehicle {
	drive(): void {
		console.log('run run');
	}
	
	protected honk(): void {
		console.log('beep');
	}
}

class Car extends Vehicle {
	private drive(): void {
		console.log('car drive');
	}
	
	startDriving(): void {
		this.drive();
		this.honk();
	}
}

const car = new Car();
car.drive(); // error
car.startDriving();

생성자

class Vehicle {
	color: string; 
	
	constructor(color: string) {
		this.color = color;
	}
}

const vehicle = new vehicle('blue');
console.log(vehicle.color); // blue

 

상속 예제

class Vehicle {
	constructor(public color: string) {}
}

class Car extends Vehicle {
	constructor(public wheels: number, color: string) {
		super(color); // 부모 클래스로 전달되므로 적용이 된다
	}
}

const car = new Car(4, 'blue');

 

인터페이스

  • 새로운 타입을 만들어서, 객체의 프로퍼티 명과 값의 타입을 서술
const oldCar = {
	name: 'Hyundai',
	year: 2000,
	broken: true
}

const printVehicle = (vehicle: { name: string; year: number; broken: boolean; }) => {
	console.log(`Name: ${vehicle.name}`);
}

printVehicle(oldCar);
  • 속성이 계속 늘어가면…?
interface Vehicle {
	name: string;
	year: number;
	broken: boolean;
}

const printVehicle = (vehicle: Vehicle) => {
	console.log(`Name: ${vehicle.name}`);
}

printVehicle(oldCar);
  • 메서드도 들어갈 수 있다.
interface Vehicle {
	name: string;
	year: number;
	broken: boolean;
	summary(): string;
}

const oldCar = {
	name: 'Hyundai',
	year: 2000,
	broken: true
	summary(): string {
		return `Name: ${this.name}`
	}
}

const printVehicle = (vehicle: Vehicle) => {
	console.log(vehicle.summart());
}

 

인터페이스 왜 사용할까?

  • 타입 어노테이션을 좀 더 함축적으로 쓸 수 있다.
  • 재사용!!
    • 설계 관점에서 코드를 간결하고 가독성도 높일 수 있다.
interface Vehicle {
	run(): string;
}

const oldCar = {
	name: 'Hyundai',
	year: 2000,
	broken: true
	run(): string {
		return `Name: ${this.name}`
	}
}

const motorCycle = {
	name: 'Honda',
	color: 'blue',
	sound: 'noisy'
	run(): string {
		return `Color: ${this.color}`
	}
}

const printVehicle = (vehicle: Vehicle) => {
	console.log(vehicle.run());
}

printVehicle(oldCar);
printVehicle(motorCycle);