반응형

이 글에서는 typescript 환경에서 type또는 interface를 그대로 가져오며 타입 재정의가 필요한 속성을 재정의 하는 방법을 다룬다.

 

type의 경우

예를 들어 아래와 같은 Test1 타입이 있다고 가정한다.

type Test1 = {
    test1: string,
    test2: string,
    test3: number,
};
const test1: Test1 = {test1: 'test1', test2: 'test2', test3: 3};

이 때 Test1의 속성인 test3를 string 바꾼 새로운 타입이 필요하다고 가정한다. 그럴 때 아래와 같은 코드를 적용하면 된다.

type Test2 = Omit<Test1, 'test3'> & { test3: string };
const test2: Test2 = {test1: 'test1', test2: 'test2', test3: 'test3'};

Omit을 사용해서 test3의 속성을 제거한 타입을 가져온 후 test3를 다시 정의해 주는 방식으로 타입을 지정할 수 있다.

 

interface의 경우

인터페이스의 경우도 동일하게 Omit을 사용해서 제거 후 재정의 하는 방식이다.

하지만 type과 interface가 다른만큼 문법이 약간 다르다.

아래와 같은 Test1 interface가 있다고 가정한다.

interface Test1 {
        test1: string;
        test2: string;
        test3: number;
    }
const test1: Test1 = {test1: 'test1', test2: 'test2', test3: 3};

이 때 type의 경우와 마찬가지로 Test1의 test3속성을 string으로 바꾼 새로운 타입이 필요하다고 가정한다. 그럴 때 아래와 같은 코드를 적용하면 된다.

interface Test2 extends Omit<Test1, 'test3'> {
     test3: string;
    }
const test2: Test2 = {test1: 'test1', test2: 'test2', test3: 'test3'};

Omit을사용해서 test3를 제거한 타입을 상속받고 test3를 재정의 하는 방식으로 interface를 지정할 수 있다.

위와 같은 상황은 이런 경우에 도움이 될 수 있다.

  • 최상위 타입에서 일부만 타입이 다른 타입이 필요한 경우
  • 나머지 속성의 타입은 똑같은데 일부만 타입이 다른경우

 

출처: https://stackoverflow.com/questions/41285211/overriding-interface-property-type-defined-in-typescript-d-ts-file/51507473#51507473

 

Overriding interface property type defined in Typescript d.ts file

Is there a way to change the type of interface property defined in a *.d.ts in typescript? for example: An interface in x.d.ts is defined as interface A { property: number; } I want to chang...

stackoverflow.com

 

반응형
얼은펭귄