몇 가지 공통점이 있는 Typescript 인터페이스를 구별할 수 있어야 하는 경우가 많습니다. 다음 예를 들어보세요.
interface Vehicle { weight: number; wheels?: number; class?: 'A' | '1' | '2' | '3';
}
우리의 응용 프로그램에는 다른 차량이 있습니다. 예를 들어 트럭의 경우 무게와 바퀴 수를 추적하려고 합니다. 그러나 다른 차량(예: yatches)에는 바퀴가 없지만 'A', '1', '2' 또는 '3' 값을 가질 수 있는 문자열인 클래스와 같이 알고 싶은 다른 속성이 있습니다. .
좋은 구성은 다음과 같다고 생각할 수 있습니다.
interface Truck { weight: number; wheels: number;
} interface Yatch { weight: number; class: 'A' | '1' | '2' | '3';
} export type Vehicle = Truck | Yatch;
그러나 이 설정을 사용하면 문제가 발생합니다. Vehicle
사물:
보시다시피 Typescript는 입력 객체가 Truck
또는 Yatch
, 다음 오류가 발생합니다.
Property 'wheels' does not exist on type 'Yatch'
객체의 유형을 어떻게 좁힐 수 있습니까? 최소한 3가지 대안이 있습니다.
1. 새로 만들기 type
각 인터페이스의 속성
interface Truck { weight: number; wheels: number; type: 'truck';
} interface Yatch { weight: number; class: 'A' | '1' | '2' | '3'; type: 'yatch';
} export type Vehicle = Truck | Yatch;
이것은 차별적 노동 조합 타입스크립트에서. 이 솔루션은 인터페이스에 이미 type
속성을 미리.
사용시 Vehicle
이제 스위치 케이스를 사용하여 두 인터페이스를 구분할 수 있습니다.
유형에 대한 인터페이스 대신 클래스를 사용하는 경우 다음 대체 구문은 정확히 동일한 결과를 생성합니다.
class Truck { weight: number; wheels: number; readonly type = 'truck';
} class Yatch { weight: number; class: 'A' | '1' | '2' | '3'; readonly type = 'yatch';
} export type Vehicle = Truck | Yatch;
2. 타입 가드 사용
유형 가드 유형 축소에 도움이 되는 함수입니다.
interface Truck { weight: number; wheels: number;
} interface Yatch { weight: number; class: 'A' | '1' | '2' | '3';
} export type Vehicle = Truck | Yatch; export function isTruck(arg: any): arg is Truck { return !!arg.weight && !!arg.wheels;
} export function isYatch(arg: any): arg is Yatch { return !!arg.weight && !!arg.class;
}
If isTruck(object)
반품 true
, 그것은 우리의 객체가 실제로 Truck
. 애플리케이션의 어느 곳에서나 이러한 기능을 가져와 사용할 수 있습니다.
그러나 이 설정에는 작은 문제가 있습니다. 여전히 빌드할 수 있습니다. Vehicle
그렇지 않은 객체 Truck
...도 아니다 Yatch
:
3. "절대" 사용
이 마지막 문제를 해결하기 위해 다음을 사용할 수 있습니다. 전에, never
Typescript 2.0에 도입된 유형. 인터페이스에 유형의 속성이 있는 경우 never
, 그 속성은 그 인터페이스를 따르는 어떤 객체에도 정의될 수 없습니다.
interface Truck { weight: number; wheels: number; class?: never;
} interface Yatch { weight: number; wheels?: never; class: 'A' | '1' | '2' | '3';
} export type Vehicle = Truck | Yatch;
유형 가드는 이전과 동일하게 작동하지만 지금은 생성할 수 없습니다. Vehicle
두 가지를 동시에 가지고 있는 객체 wheels
과 class
속성 :
보시다시피 다음 오류가 발생합니다.
Type 'number' is not assignable to type 'never'
Check the Spanish version of this post at my blog cibetrucos.com
Source: https://www.codementor.io/davidsilvasanmartin/typescript-discriminated-unions-1jhqp24mvx