TypeScript 배우기3

Parker.Park·2022년 7월 29일
0

TypeScript

목록 보기
3/8

타입스크립트 시작하기, Inflearn


강의를 들으면서 중간중간 취업준비를 하고 있다. 체크해야 할것들이 많고, 다시 공부해야 할 것도 차곡차곡 쌓인다. 자주 사용했던 말들이지만 이럴 때일 수록 차근차근 해나가야 할 것이다. 더위가 깊어졌다.

static

static 키워드는 클래스의 정적메소드를 정의한다고 한다. 정적 메소드는 클래스의 인스턴스가 아닌, 클래스 이름으로 호출한다고 한다. 클래스가 인스턴스를 생성하지 않아도 정적(static) 메소드는 호출 할 수 있다고 한다.
접근 제한자(public, private, protected)와 readonly, static그리고 이어서 알아볼 abstract 과 같은 키워드들이 어느정도는 JavaScript에도 있는 개념이다. 그러나 TypeScript에 좀더 구체적으로 정리되어 있기때문에 여기서 먼저 정리하는것이 좋다고 생각한다.

class Dog {
  constructor(public name: string) {}

  static staticMethod() {
    /*
    정적 메소드에서는 this를 사용할 수 없다고 한다.
    */
    return `this is static`;
  }

  generalMethod() {
    return this.name;
  }
}

//정적 메소드는 클래스 이름으로 호출한다.
console.log(Dog.staticMethod()); // this is static

const dog1 = new Dog("Maltese");
console.log(dog1.staticMethod());

//error TS2576: 
//Property 'staticMethod' does not exist on type 'Dog'.

TypeScript에서 static 키워드는 클래스 property에도 적용 가능하다고 한다. 또한 정적메소드와 마찬가지로 인스턴스를 생성하지 않고도 클래스 이름으로 호출 가능하다.

class Person {
  static personNum = 0;
  constructor() {
    //생성자 호출시 증가
    Person.personNum++;
  }
}

console.log(Person.personNum); // 0

const person1 = new Person();
const person2 = new Person();

console.log(Person.personNum);// 2

abstract

추상클래스는 직접적으로 인스턴스를 가질수 없다.

abstract class Animal {
  constructor(public name: string) {}

  getName(): void {
    console.log(`${this.name}`);
  }
}

const animal1 = new Animal("Maltese");
//error TS2511: Cannot create an instance of an abstract class.

추상 클래스는 하나 이상의 추상 메소드를 가질수 있으며 일반 메소드 또한 가질 수 있다. 추상 메소드는 내용이 없이 메소드 이름과 타입만 선언된 메소드를 의미한다고 한다. 추상클래스는 인스턴스를 가질 수 없기 때문에 상속만을 위해 사용한다고 볼 수 있을것이다. 추상 클래스에 추상 메소드가 있을 경우 상속된 클래스에는 추상 메소드를 반드시 구현하여야한다.

abstract class Animal {
  constructor(public name: string) {}

  getName(): void {
    console.log(`${this.name}`);
  }

  abstract sayHello(): void;
}

class Dog extends Animal {
  bark(){
    console.log("Mung!")
  }
  //추상클래스의 추상 메소드를 구현하지 않을 경우 에러가 발생한다.
    sayHello() {
    console.log("Hello");
  }
}


const dog1 = new Dog("ddoddo");
dog1.sayHello(); // Hello
dog1.getName(); // ddoddo

참조

[클래스, PoiemaWeb, 2022년07월30일 접속]
https://poiemaweb.com/typescript-class

profile
개발자준비중

0개의 댓글