본문 바로가기

Frontend/TS

[TS] TypeScript Class,Interface,

728x90
타입스크립트의 마지막 개념인
Class와 Interface에 대한 기록을 남기려고 한다.

Class

개요

  • Class는 객체 생성을 위한 템플릿이다. 
class People{
	constructor(n,a){
    	this.name=n;
        this.age=a;
        }
  }
  
  const choi=new People('choi',100)
  console.log(choi);
  //People {name: 'choi', age: 100}
  • JS에서는 위와 같이 class를 사용한다.
  • 그럼 TypeScript에서는 다르게 사용할까?
class People{
	constructor(
    	public name:string,
        public age:number
        ){}
    }
  • TS에서는 접근제어자(public), 변수 이름(name), 타입(string)을 써주면 위에서의 작업을 해준다.
접근제어자
  선언한 클래스 상속받은 클래스 인스턴스
public
protected
private
해당 접근제어자를 사용한 변수에 접근할 수 있는 곳은 위와 같다.
  • 즉 위 두 코드가 같은 기능을 하는 것이다.

추상 클래스

  • 상속을 위한 추상 클래스도 있다.
  • 추상 클래스는 직접 인스턴스를 생성하지 못하고, 다른 클래스에게 상속해주는 것만 가능한 클래스이다.
abstract class People{
constructor(
		private firstName:string,
		private lastName:string,
	) {}
}
  • 위와 같이 생성 abstract를 붙여서 생성한다.
class Player extends People{}
  • 추상 클래스를 생성하면 위와 같이 다른 클래스에 상속할 수 있다.
  • 상속된 클래스를 통해서만 인스턴스를 생성할 수 있다.

Interface

개요

  • interface는 TS에게 객체의 모양에 대해 설명하는 역할을 한다.
  • 공식문서에 나와있듯 interface와 type은 많은 유사점을 가지고 있는데
    • interface는 class와 object의 모양
    • type은 그 외의 기능
  • 위처럼 사용되는 것이 일반적이다.

특징

  • interface는 TS에서 JS로 변환되었을 때는 볼 수 없다.

  • 위와 같이 interface로 객체의 모양을 설명해줬지만, JS 코드에서는 볼 수 없는 것을 확인할 수 있다.
  • 이를 이용해 추상 클래스 역할을 하기도 한다.
interface People{
	firstName:string,
	lastName:string,
	getFullName():string,
}

class Player implements User{
	constructor(
		public firstName:string,
		public lastName:string,
	){}
	getFullName(){return `${firstName} ${lastName}`}
}
  • interface는 JS파일에는 남지 않기 때문에 추상 클래스의 역할을 해주면서 파일의 크기를 줄일 수 있다.
  • 하지만 protected, private 접근제어자를 쓸 수 없고, interface 내부에서 constructor를 작성할 수 없다는 단점이 있다.

지금까지 기록한 class, interface, generic을
모두 사용해서 generic Storage를 구현해보자!
  • 먼저 interface로 storage 객체의 모양을 만들어보자
interface SStorage<T> {
  [key: string]: T;
}
  • T라는 type을 사용해서 key의 type은 string, value의 타입은 T인 객체로 지정했다.
  • 이제 GenericStorage class를 만들어보자
class GenericStorage<T> {
  private storage: SStorage<T> = {};
  }
  • T라는 type을 사용해 빈 객체를 생성했는데 이 객체의 모양은 위에 만든 SStorage이다.
  • SStorage의 generic에 앞서 정했던 T type을 사용했다.
  • get, set, update, remove, clear 메서드를 구현해보자
class GenericStorage<T> {
  private storage: SStorage<T> = {};
  get(key: string) {
    if (this.storage[key]) return this.storage[key];
    return undefined;
  }
  set(key: string, value: T) {
    if (this.get(key)) {
      throw Error("Key Duplication!");
    } else {
      this.storage[key] = value;
    }
  }
  update(key: string, newValue: T) {
    if (this.get(key)) {
      this.storage[key] = newValue;
    } else {
      throw Error("Wrong Key!");
    }
  }
  remove(key: string) {
    if (this.get(key)) {
      const delValue = this.storage[key];
      delete this.storage[key];
      return delValue;
    } else {
      throw Error("Wrong key!");
    }
  }
  clear() {
    this.storage = {};
  }
}
  • 위처럼 generic T를 이용해 유동적인 Storage를 만들었다.
728x90

'Frontend > TS' 카테고리의 다른 글

[TS] tsconfig.json,정의 파일(d.ts),JSDocs  (0) 2022.11.21
[TS] TypeScript Alias Type,Call Signature,Generic  (0) 2022.11.17