[typescript] class

Hyo Kyun Lee·2021년 9월 16일
0

typescript

목록 보기
4/5

1. class (extended interface)

컴파일에서 반영되는 속성/인자의 집합
interface에서 확장된 넓은 개념으로, interface와 동일한 목적으로 활용한다.

interface Human{
  name: string,
  age: number,
  job: string
}
  • interface는 인자의 type만 정의해준다.
class Human{
    public name: string
    public age: number
    public job: string
}
  • class는 인자의 type과 속성(public, private)를 모두 정의해준다.

2. constructor

class를 통한 객체 생성, 호출 등 초기화를 할 때마다 실행되는 메소드의 일종

class Human{
    public name: string
    public age: number
    public job: string
    constructor(name: string, age: number, job: string){
        this.name = name
        this.age = age
        this.job = job
    }
}
  • 생성자를 통해 인스턴스를 생성할 수 있고, 이 인스턴스는 class 재활용(인자 및 객체 생성)을 할 수 있다.

3. class 활용

class를 생성하고, 해당 class를 이용하여 새로운 객체를 생성할 수 있다.

class Human{
    public name: string
    public age: number
    public job: string
    constructor(name: string, age: number, job: string){
        this.name = name
        this.age = age
        this.job = job
    }
}
const person1 = new Human("LEE HYO KYUN", 15, "Developer")

const foo = (Human) => {
    return `HELLO ${Human.name}(_${Human.age})! How are your ${Human.job} going?`
}

console.log(foo(person1))

export {}
  • person1처럼 class를 활용하여 동일한 형태의 객체를 생성할 수 있다.
  • 동일한 형태의 객체를 생성하기 위해선 class의 인스턴스가 반드시 필요하고, class의 생성자와 속성이 그 역할을 한다.
  • python에서의 class와 형태가 매우 유사하고, 객체지향 프로그래밍 언어에서의 구조와 거의 동일하다.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Human {
    constructor(name, age, job) {
        this.name = name;
        this.age = age;
        this.job = job;
    }
}
const person1 = new Human("LEE HYO KYUN", 15, "Developer");
const foo = (Human) => {
    return `HELLO ${Human.name}(_${Human.age})! How are your ${Human.job} going?`;
};
console.log(foo(person1));
//# sourceMappingURL=index.js.map
  • 컴파일 이후의 코드인 index.js를 보면, class가 그대로 반영되었음을 확인할 수 있다.

4. class의 private 속성

private 속성의 인자는 별도로 생성한 객체(new class)를 통해서가 아닌, 반드시 class 자체적으로 접근해야 한다.

class Human{
    private name: string
    public age: number
    public job: string
    constructor(name: string, age: number, job: string){
        this.name = name
        this.age = age
        this.job = job
    }
}

const person1 = new Human("LEE HYO KYUN", 15, "Developer")

const foo = (person: Human) => {
    return `HELLO ${person.name}(_${person.age})! How are your ${person.job} going?`
}

console.log(foo(person1))

위 코드에서 Human class의 name 속성은 private로 정의되어 있다.

src/index.ts(15,28): error TS2341: Property 'name' is private and only accessible within class 'Human'.

Human의 new class를 생성한 후 별도의 객체가 아닌, Human class 자체적으로만 접근이 가능하다.

위 상태에서 해당 인자에 접근하려고 하면 위와 같은 오류가 발생한다.

const foo = (Human) => {
    return `HELLO ${Human.name}(_${Human.age})! How are your ${Human.job} going?`
}

class 자체적으로 접근한다는 것은, 말 그대로 class를 직접 호출하는 것이다.

위와 같이 person 객체로 접근하는 부분을 class로 직접 접근하는 방식으로 바꾸면, 정상적으로 해당 인자를 활용할 수 있게 된다.

5. class vs interface

class

React, node.js 등 문법/구조적인 혼용 측면에서는 class 사용을 권장한다.

interface

typescript 측면에서는 interface가 안정적이다.

6. 참조링크

javascript class
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes

0개의 댓글