Class in TypeScript

해당 내용은 TypeScript 공식 문서를 학습한 내용입니다. 오류나 궁금하신 점이 있다면 언제든지 댓글로 남겨주세요!
Oct 25, 2023
Class in TypeScript
목차
👩‍💻
해당 내용은 TypeScript 공식 문서를 학습한 내용입니다. 오류나 궁금하신 점이 있다면 언제든지 댓글로 남겨주세요!
필자는 ExpressJS로만 계속 개발을 해오다가 최근 NestJS로 프로젝트를 하자는 지인의 의견으로 본격적인 프로젝트 돌입에 앞서 NestJS 공부를 시작했다.
어느 정도 Class에 대해 제대로 이해하고 있다고 생각했는데 막상 써보려고 하니 생각보다 헷갈리는 점이 많았다. 서치해가면서 NestJS 공식 문서를 따라가던 중 제대로 한 번 정리해야 겠다는 생각에 이 글을 쓴다.

Class Members

Definition of Class

클래스는 객체를 만드는 하나의 형식(form)이며, 데이터를 캡슐화 시킨다.
Classes are a template for creating objects. They encapsulate data with code to work on that data. - MDN

Fields

따라서, 아래의 pt 처럼 객체에서 요소들을 꺼내오듯 사용할 수 있다.
  • 선언된 x와 y는 프로퍼티(property)라고 부른다.
  • 프로퍼티가 선언된 곳을 필드(fields)라고 부른다.
class Point { x: number; y: number; } const pt = new Point(); pt.x = 0; pt.y = 0;
 
🔥 타입스크립트에서는 프로퍼티를 선언하기 전에 프로퍼티의 변수에 해당하는 값들의 타입을 미리 지정해주어야 한다.
Note that the field needs to be initialized in the constructor itself. TypeScript does not analyze methods you invoke from the constructor to detect initializations, because a derived class might override those methods and fail to initialize the members.
  • 주의할 점은 타입스크립트에서 프로퍼티는 생성자(constructor)안에서만 선언하고 초기화할 수 있다.
  • 왜냐하면 파생 클래스(dereived class)가 메서드(method)를 무효시키고 프로퍼티 초기화에 실패할 수 있기 때문이다.
    • 파생 클래스는 말 그대로 상위 클래스에서 파생된 클래스이다. 파생클래스는 상위 클래스의 모든 멤버 변수와 함수를 상속(inheritance) 받는다.
    • 상속이란, 추상화, 캡슐화와 더불어 객체 지향 프로그래밍을 구성하는 중요한 특징 중 하나이다. 상속을 통해 기존에 작성된 클래스를 재활용할 수 있고, 공통적으로 사용되는 부분을 상위 클래스에 미리 작성함으로서 파생 클래서에서 중복되는 부분을 미리 제거할 수 있다.
class GoodGreeter { name: string; constructor() { this.name = "hello"; } }

readonly

Fields may be prefixed with the readonly modifier. This prevents assignments to the field outside of the constructor.
readonly modifier를 이용하여 이미 선언된 프로퍼티 값이 밖에서 수정되는 것을 막을 수 있다.
class Greeter { readonly name: string = "world"; constructor(otherName?: string) { if (otherName !== undefined) { this.name = otherName; } } } const g = new Greeter(); g.name = "also not ok"; // Cannot assign to 'name' because it is a read-only property.

Constructors

Class constructors are very similar to functions. You can add parameters with type annotations, default values, and overloads.
  • 클래스의 생성자(constructor)는 함수와 매우 비슷하다.
  • 인수(parameter)를 추가할 수 있고, 타입, 기본값이나 오버로드(overload)를 선언할 수 있다.
    • 오버로드는 이름이 같은 두 세개의 메서드가 다른 인자나 인수를 받아 다른 역할을 하는 것을 말한다.
class Point { x: number; y: number; // Normal signature with defaults constructor(x = 0, y = 0) { this.x = x; this.y = y; } }
There are just a few differences between class constructor signatures and function signatures:
  • Constructors can’t have type parameters - these belong on the outer class declaration, which we’ll learn about later
  • Constructors can’t have return type annotations - the class instance type is always what’s returned
생성자와 함수에는 두가지 다른점이 있다. 생성자에서는 파라미터와 리턴값에 타입을 지정하지 못한다. 파라미터의 경우, 다른 클래스에서 지정하기 때문이고, 리턴 값은 클래스 인스턴스가 리턴하는 그 값이 타입 그자체이기 때문이다.

Super Calls

Just as in JavaScript, if you have a base class, you’ll need to call super(); in your constructor body before using any this. members:
자바스크립트와 마찬가지로 타입스크립트에서도 생성자 내에서 this를 사용하기전에 super()를 호출 해야한다.

Methods

A function property on a class is called a method. Methods can use all the same type annotations as functions and constructors.
함수 프로퍼티를 클래스에서는 메서드(method)라고 한다. 메서드는 함수나 생성자에 같은 타입을 지정할 수 있다.
class Point { x = 10; y = 10; scale(n: number): void { this.x *= n; this.y *= n; } }
Other than the standard type annotations, TypeScript doesn’t add anything else new to methods.
Note that inside a method body, it is still mandatory to access fields and other methods via this.. An unqualified name in a method body will always refer to something in the enclosing scope:
타입 지저을 제외 하고는, 타입스크립트에서는 메서드에 더 새로운 것을 추가하지 않는다.
알아야 할 것은, 메서드 내부 바디에서는 필드에 접근이 가능 하고, 다른 메서드에도 this를 이용해서 접근할 수 있다.
let x: number = 0; class C { x: string = "hello"; m() { // This is trying to modify 'x' from line 1, not the class property x = "world"; // Type 'string' is not assignable to type 'number'. } }

References

Share article
RSSPowered by inblog