那么,类型定义:
// type definitions
class GenericDto {
public ids: string[] = [];
public dateFrom: string | null = null;
public dateTo: string | null = null;
}
class FleetInformationDto extends GenericDto { }
class VehicleInformationDto extends GenericDto { }
enum ReportQueueAction {
GENERATE
}
enum ReportQueueType {
VEHICLE_INFORMATION,
FLEET_INFORMATION
}
type ReportQueue = {
action: ReportQueueAction;
type: ReportQueueType.FLEET_INFORMATION;
dto: FleetInformationDto
} | {
action: ReportQueueAction,
type: ReportQueueType.VEHICLE_INFORMATION,
dto: VehicleInformationDto;
}
实现和执行:
// implementation
const dto: FleetInformationDto = {
ids: ["1", "2"],
dateFrom: '2021-01-01',
dateTo: '2021-02-01'
}
const queueData: ReportQueue = {
action: ReportQueueAction.GENERATE,
type: ReportQueueType.FLEET_INFORMATION,
dto: dto
}
// ^ works as expected
但是如果我们将 "VehicleInformationDto" 添加到类型 FLEET_INFORMATION 中,它将不会抛出错误。
const dto2: VehicleInformationDto = {
ids: ["1", "2"],
dateFrom: '2021-01-01',
dateTo: '2021-02-01'
}
const queueData2: ReportQueue = {
action: ReportQueueAction.GENERATE,
type: ReportQueueType.FLEET_INFORMATION,
dto: dto2 // <-- no error thrown here
}
好的,那么这里有什么问题吗?我有什么遗漏吗?
问题是:为什么我可以在 queueData2
中将 VehicleInformationDto
分配给 dto
,而 TypeScript 却希望它是 FleetInformationDto
?
编辑:好的,是的,那是因为它们共享相同的属性,那么我怎么添加检查呢?
VehicleInformationDto
可分配给FleetInformationDto
,因为它具有完全相同的属性。 - user13258211type A = { foo: number }
和type B = { foo: number }
是相同的类型。在这里查看更多信息 - Jared Smith