981377660LMT / ts

ts学习
6 stars 1 forks source link

区别联合类型:联合是未标记的,并且应该在 TypeScript 中进行区分:不可判定、崩溃和反模式 #398

Open 981377660LMT opened 1 year ago

981377660LMT commented 1 year ago

https://www.hacklewayne.com/unions-are-untagged-and-should-be-discriminated-in-typescript-undecidable-collapse-and-anti-patterns

981377660LMT commented 1 year ago

如果对于联合体中的每个类型,所有字段都是可选的,那么联合体类型就无法区分。

981377660LMT commented 1 year ago

实际上,这个示例可以通过惯用的方式修复 - 手动添加和强制执行标签。

981377660LMT commented 1 year ago
type EntityA = { type: 'A', payload?: Record<string, any> };
type EntityB = { type: 'B', payload?: string[] };
981377660LMT commented 1 year ago

We arrive at a simple guide to the use of untagged unions: think first about discriminators when putting types in a union. If we expect the discriminator to be difficult to write, then the union is bad, or, not blessed :-) 我们得出了使用未标记联合的简单指南:在将类型放入联合时首先考虑鉴别器。如果我们预计判别器很难编写,那么联合就是不好的,或者说,不幸运:-)