2021년 2월 5일 금요일

[Typescript] 제공되는 객체타입에 메소드 추가하기.(prototype에 메소드 추가하기)

Javascript의 Array, Date 같은 기본 타입은 interface로 정의되어 있다.

Typescript의 interface는 선언 병합(declaration-merging)이라는걸 지원하는데, 다음과 같은거다.

선언병합

1
2
3
4
5
6
7
8
9
10
interface Box {
  height: number;
  width: number;
}
 
interface Box {
  scale: number;
}
 
let box: Box = { height: 5, width: 6, scale: 10 };
cs

위 코드에서 보면 interface Box를 두번 선언했는데, 두 선언이 병합되었다.

위의 방식으로 Array, Date같은 기본 타입에 함수를 추가할 수 있다.

우선 추가한 메소드를 Typescript에서 오류 없이 사용하려면 d.ts에 추가를 해줘야한다.

d.ts

1
2
3
declare interface Array<T> {
    deepCopy(): Array<T>;
}
cs

그리고 구현부를 추가하려면 각 타입의 prototype에 함수를 만들어주면 된다.(클래스 상속 또는 인터페이스 상속과 다른 개념이다.)

1
2
3
4
5
6
7
Array.prototype.deepCopy = function() {
    let newArray: any[] = [];
    for(let i = 0; i < this.length; i++) {
        newArray.push(this[i]);
    }
    return newArray;
}
cs



댓글 없음: