Voyage_dev
항해하는 개발자
Voyage_dev
전체 방문자
오늘
어제
  • All (158)
    • Front-End (102)
      • HTML & CSS (7)
      • JavaScript (13)
      • Web & 표준 & ETC (15)
      • React (17)
      • Next (13)
      • TypeScript (6)
      • Zustand (1)
      • AWS (4)
      • Redux (1)
      • MobX (9)
      • GraphQL (1)
      • Flutter (15)
    • 알고리즘 (12)
      • Java (11)
      • JavaScript (1)
    • Git (1)
    • Project (2)
      • 개인 (1)
      • 팀 (1)
    • Books (30)
      • 누구나 자료구조와 알고리즘 (20)
      • Do It 타입스크립트 프로그래밍 (9)
    • 자료구조 (6)
    • 취업 (1)
    • 항해플러스 (1)
      • 1주 (1)

블로그 메뉴

  • 👨🏻‍💻 Github
  • 💻 Rss 블로그
  • 🏊‍♂️ Resume
  • 🗂️ Portfolio

인기 글

최근 댓글

hELLO · Designed By 정상우.
Voyage_dev

항해하는 개발자

타입스크립트 클래스 & 인터페이스
Front-End/TypeScript

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

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);

'Front-End > TypeScript' 카테고리의 다른 글

유틸리티 타입  (3) 2024.07.24
제네릭 & 타입 가드  (2) 2024.07.24
타입 어노테이션 & 추론  (2) 2024.07.24
타입스크립트란 무엇인가  (2) 2024.07.24
[Typescript] 타입스크립트란?  (1) 2022.12.14
    'Front-End/TypeScript' 카테고리의 다른 글
    • 유틸리티 타입
    • 제네릭 & 타입 가드
    • 타입 어노테이션 & 추론
    • 타입스크립트란 무엇인가
    Voyage_dev
    Voyage_dev

    티스토리툴바