Class & Interface

Juhwan Lee·2022년 5월 9일
0

Learning TypeScript

목록 보기
3/5
post-thumbnail

What’s Object-oriented Programming(OOP)?

OOP: 객체 지향 프로그래밍

OOP는 객체를 기준으로 코드를 나누어 구현한다. 절차지향 방식보다 사람의 사고방식에 더 가깝다. 어플리케이션을 구성하는 요소들을 객체로 바라보고, 유기적으로 연결하여 프로그래밍하는 것이다.

Classes & Instances

  • Class: Object들의 청사진, 객체의 형태, 포함해야 할 속성과 메서드를 정의하는 데 도움이 된다.
  • Object: 클래스의 인스턴스

→ 클래스는 객체의 생성 속도를 높여주며 객체 리터럴 표기법의 대안이다.

Class

  • 간단한 Class 만들기
class Department {
  name: string; // Obeject가 아닌 class의 field

  constructor(n: string) {
    this.name = n;
  }
}

const accounting = new Department('Accounting');

console.log(accounting);
  • ES6로 complie
"use strict";
class Department {
    constructor(n) {
        this.name = n;
    }
}
const accounting = new Department('Accounting');
console.log(accounting);
  • ES5로 compile
"use strict";
var Department = (function () {
    function Department(n) {
        this.name = n;
    }
    return Department;
}());
var accounting = new Department('Accounting');
console.log(accounting);

✨ 코드는 명확하게 정의하는 것이 좋다!
일단 몇 주를 쉬게 된다면 의도를 잊어버릴 수도 있고, 다음으로 팀에서 일하거나 동료들과 코드를 공유할 수 있으니, 의도를 명확하게 작성해야한다

Interface

interface Person {
  name: string;
  age: number;

  greet(phrase: string): void;
}

let user1: Person;

user1 = {
  name: 'Max',
  age: 30,
  greet(phrase: string) {
    console.log(phrase + ' ' + this.name);
  },
};

user1.greet('Hi there, I am');

interface를 type으로 바꿔도 똑같이 동작한다.

type Person =  {
  name: string;
  age: number;

  greet(phrase: string): void;
}

let user1: Person;

user1 = {
  name: 'Max',
  age: 30,
  greet(phrase: string) {
    console.log(phrase + ' ' + this.name);
  },
};

user1.greet('Hi there, I am');

그러면 왜 interface를 사용할까?

인터페이스와 사용자 정의 타입은 완전히 같지 않다
interface는 객체의 구조를 설명하기 위해서만 사용한다

→ type은 보다 유연하다, 한편으로는 interface가 더 깔끔할 수도 있다
→ 실제로 type보다 interface를 더 자주 사용한다.
→ class가 인터페이스를 이행하고 준수해야 하는 약속처럼 사용할 수 있다

// type AddFn = (a: number, b: number) => number;
interface AddFn {
  (a: number, b: number): number;
}

let add: AddFn;

add = (n1: number, n2: number) => {
  return n1 + n2;
};

interface Named {
  readonly name?: string;
  outputName?: string;
}

interface Greetable extends Named {
  greet(phrase: string): void;
}

class Person implements Greetable {
  name?: string;
  age = 30;

  constructor(n?: string) {
    if (n) {
      this.name = n;
    }
  }

  greet(phrase: string) {
    if (this.name) {
      console.log(phrase + ' ' + this.name);
    } else {
      console.log('Hi!');
    }
  }
}

let user1: Greetable;

user1 = new Person();
// user1.name = 'Manu';

user1.greet('Hi there - I am');
console.log(user1);

(JS) 클래스 관련 추가 정보
TS 인터페이스 관련 추가 정보

profile
keep going

0개의 댓글