简体   繁体   English

Typescript union 类型不抛出错误

[英]Typescript union type does not throw error

So, type definitions:所以,类型定义:

// 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;
}

and implementation:和实施:

// 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

but if we add "VehicleInformationDto" to type FLEET_INFORMATION it does not throw error但是如果我们添加“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
}

well, what's the catch here?好吧,这里有什么问题? am i missing something?我错过了什么吗?

The question: Why am I able to assign VehicleInformationDto to dto inside queueData2 when typescript expects it to be FleetInformationDto ?问题:为什么当 typescript 期望它是queueData2时,我可以将VehicleInformationDto分配给FleetInformationDto内的dto

Edit: OK, yeah, it's because they share the same properties, then, how could I add a check for that?编辑:好的,是的,这是因为它们共享相同的属性,那么,我该如何添加检查呢?

Playground 操场

Typescript is structurally typed, not nominally typed . Typescript 是结构类型的,不是名义上的类型 This means that as far as Typescript is concerned these are the same type:这意味着就 Typescript 而言,这些是相同的类型:

class FleetInformationDto extends GenericDto { }
class VehicleInformationDto extends GenericDto { }

While I think this is absolutely the correct choice for adding static typing to a language like Javascript where objects are a grab-bag of properties, it can lead to some subtle gotchas:虽然我认为这绝对是将 static 类型添加到像 Javascript 这样的语言(其中对象是属性的抓包)中的正确选择,但它可能会导致一些微妙的陷阱:

interface Vec2 {
  x: number
  y: number
}

interface Vec3 {
  x: number
  y: number
  z: number
}

const m = { x: 0, y: 0, z: "hello world" };
const n: Vec2 = m; // N.B. structurally m qualifies as Vec2!
function f(x: Vec2 | Vec3) {
  if (x.z) return x.z.toFixed(2); // This fails if z is not a number!
}
f(n); // compiler must allow this call

Here we're doing some graphics programming and have 2D and 3D vectors, but we have a problem: objects can have extra properties and still structurally qualify which leads to a problem in this union type (sound familiar?).在这里,我们正在做一些图形编程并且有 2D 和 3D 向量,但是我们有一个问题:对象可以有额外的属性并且仍然在结构上限定,这会导致这种联合类型的问题(听起来很熟悉?)。

The answer in your particular case is to use a discriminant to easily distinguish the similar types in the union:在您的特定情况下,答案是使用判别式轻松区分联合中的相似类型:

interface FleetInformationDto extends GenericDto {
    // N.B., fleet is a literal *type*, not a string literal
    // *value*.
    kind: 'fleet'
}

interface VehicleInformationDto extends GenericDto {
    kind: 'vehicle'
}

Here I've used strings, but any unique compile-time constant (any primitive value or members of an enum ) will do.这里我使用了字符串,但任何唯一的编译时常量(任何原始值或enum的成员)都可以。 Also, since you're not instantiating your classes and using them purely as types I've made them interfaces but the same principles apply.此外,由于您没有实例化您的类并将它们纯粹用作类型,因此我将它们设为接口,但适用相同的原则。

Playground 操场

And now you can clearly see the error that type 'fleet' is not assignable to type 'vehicle'.现在您可以清楚地看到“车队”类型不可分配给“车辆”类型的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 TypeScript 在检查联合类型的 if 语句中会抛出错误,就好像它只是文字类型一样? - Why does TypeScript throw an error in an if statement checking an Union Type as if it's just a Literal Type? 打字稿 - 联合类型和泛型类型引发不兼容错误 - Typescript - Union Type and generic types throw incompatibility error Typescript参数类型不匹配不会抛出错误 - Typescript argument type mismatch does not throw error 为什么 TypeScript 不会为未定义的类型抛出编译错误 - Why does TypeScript not throw a compile error for an undefined type Typescript 在传递错误类型的 prop 时不会抛出错误 - Typescript does not throw an error when wrong type of prop is passed 为什么 Typescript 会抛出错误信息:类型上不存在属性? - Why Typescript throw error message: Property does not exist on type? 当 function 参数类型不匹配时,为什么 TypeScript 不抛出错误? - Why does TypeScript not throw an error when the function argument type is mismatched? 在Typescript Reac + Redux中具有联合类型的类型错误中,属性不存在 - Property does not exist on type error with Union Types in Typescript Reac + Redux 为什么 typescript 在这种情况下使用联合类型显示错误? - Why does typescript show an error on this scenario with a union type? 为什么我的 TypeScript 报联合类型错误? - Why does my TypeScript report an error for a union type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM