Post
TS) super와 오버로딩
2022-09-25 AM 05/05
#typescript
#study
1. supe() 메서드와 super 키워드
class Person {
constructor(public firstName: string, // 슈퍼 클래스의 생성자
public lastName: string,
private age: number) {}
}
class Employee extends Person {
constructor (firstName: string, lastName: string,
age: number, public department: string) { // 서브 클래스의 생성자
super(firstName, lastName, age); // 슈퍼 클래스의 생성자
}
}
const empl = new Employee('Joe', 'Smith', 29, 'Accounting');
마찬가지로, super 키워드를 사용해서 슈퍼 클래의 메서드도 불러와서 사용할 수 있다.
추상 클래스
추상 클래스는 객체로 만들 수 없는 추상적인 개념으로, 일종의 설계도 역할을 한다.
추상 클래스는 abstract 키워드로 선언할 수 있다.
// 하위에 abstract 메서드를 가지려면, 처음에 abstract를 적어줘야 함
abstract class Person {
constructor(public name: string){};
changeAddress(newAddress: string){
console.log(`Change address to ${newAddress}`);
}
giveDayOff() {
console.log(`Giving a day off to ${this.name}`);
}
promote(percent: number){
this.giveDayOff();
this.increasePay(percent);
}
abstract increasePay(percent: number): void;
}
// abstract 서브 클래스에서는 abstarct increasePay만 만들 수 있음
// 다른 것은 접근하지 못함
class Employee extends Person{
increasePay(percent:number){
console.log(`Increasing the salary of the ${this.name} by ${percent}` )
}
}
class Contracter extends Person{
increasePay(percent:number){
console.log(`Increasing the hourly rate of the ${this.name} by ${percent}` )
}
}
const workers: Person[] = [];
workers[0] = new Employee("힘찬");
workers[1] = new Contracter("찬힘");
workers.forEach(worker => worker.promote(5));
위처럼 상속을 통해 기능을 확장하거나, 변경하는 것을 다형성이라고 하며 객체 지향 언어의 주요한 특징이라고 카더라.
메서드 오버로딩
파라미터의 유형과 개수가 다르지만, 이름이 같은 메서드를 여러 개 가질 수 있게 만드는 것
타입 스크립트에서는 타입이 없는 메서드를 만들 수 없다. (하단 참고)
그러나 일종의 문법적 설탕으로 함수 내 파라미터 갯수를 처음보다 더 많이, 혹은 더 적게 만들 수 있다.
오버로딩의 좋지 못한 예)
class ProductService {
getProducts() {
console.log('Getting all products');
}
getProduct(id: number){
console.log(`Getting ${id}`);
}
}
const prodService = new ProductService();
prodService.getProducts(123);
prodService.getProducts();
Duplicate function 에러가 뜨지만 컴파일은 제대로 되고, 실행도 제대로 된다.
오버로딩의 좋은 예)
class ProductService{
getProducts();
getProducts(id: number);
getProdcuts(id?: number){
if(typeof id === 'number'){
console.log(`id is ${id}`)
} else {
console.log("get all products")
}
}
}
const prodService = new ProductService();
prodService.getProdcuts(123);
prodService.getProdcuts();
웃긴 것은 getProducts(), getProducts(id: number)는 없어도 오버로딩이 잘 된다. 단 자동완성을 위해서 적었다고 한다 ^^:
파라미터 및 반환되는 타입이 다른 오버라이딩
interface Product {
id: number;
description: string;
}
class ProductService {
getProducts(description: string): Product[];
getProducts(id: number): Product;
getProducts(product: number | string): Product[] | Product{
if (typeof product === "number") {
console.log(`Getting the product info for id ${product}`);
return { id: product, description: 'great product' };
} else if (typeof product === "string") {
console.log(`Getting product with description ${product}`);
return [{ id: 123, description: 'blue jeans' },
{ id: 789, description: 'blue jeans' }];
} else {
return {id: -1, description: "Error"};
}
}
}
const prodService = new ProductService();
console.log(prodService.getProducts(123));
console.log(prodService.getProducts('blue jeans'));
컴파일 된 자바스크립트
"use strict";
class ProductService {
getProducts(product) {
if (typeof product === "number") {
console.log(`Getting the product info for id ${product}`);
return { id: product, description: 'great product' };
}
else if (typeof product === "string") {
console.log(`Getting product with description ${product}`);
return [{ id: 123, description: 'blue jeans' },
{ id: 789, description: 'blue jeans' }];
}
else {
return { id: -1, description: "Error" };
}
}
}
const prodService = new ProductService();
console.log(prodService.getProducts(123));
console.log(prodService.getProducts('blue jeans'));