program tip

Typescript에서 유형을 확장 할 수 있습니까?

radiobox 2020. 10. 14. 07:40
반응형

Typescript에서 유형을 확장 할 수 있습니까?


다음 유형이 있다고 가정합니다.

type Event = {
   name: string;
   dateCreated: string;
   type: string;
}

이제이 유형을 확장하고 싶습니다.

type UserEvent extends Event = {
   UserId: string; 
}

이것은 작동하지 않습니다. 어떻게 할 수 있습니까?


이 키워드 extends는 인터페이스와 클래스에만 사용할 수 있습니다.

추가 속성이있는 유형을 선언하려는 경우 교차 유형을 사용할 수 있습니다 .

type UserEvent = Event & {UserId: string}

TypeScript 2.2에 대한 UPDATE , 이제 유형이 몇 가지 제한 사항을 충족하는 경우 객체와 유사한 유형을 확장하는 인터페이스를 가질 수 있습니다 .

type Event = {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

반대로 작동하지 않습니다 . 구문 을 사용하려면 UserEventa type아닌 인터페이스로 선언해야 extends합니다.

그리고 extend 임의의 유형과 함께 사용 하는 것은 여전히 ​​불가능합니다. 예를 들어 Event제약 조건이없는 유형 매개 변수 인 경우 작동하지 않습니다 .


유형을 교차 할 수 있습니다.

type TypeA = {
    nameA: string;
};
type TypeB = {
    nameB: string;
};
export type TypeC = TypeA & TypeB;

이제 코드 어딘가에서 다음을 수행 할 수 있습니다.

const some: TypeC = {
    nameB: 'B',
    nameA: 'A',
};

달성하려는 것은 다음과 같습니다.

interface Event {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

유형을 정의한 방식은 상속 지정을 허용하지 않지만 artem이 지적한 대로 교차 유형을 사용하여 유사한 것을 얻을 수 있습니다 .

참고 URL : https://stackoverflow.com/questions/41385059/possible-to-extend-types-in-typescript

반응형