我正在绞尽脑汁为什么以下代码无法编译:
interface Circle { type: "circle"; }
interface Rectangle { type: "rectangle"; }
type Shape = Circle | Rectangle;
interface Circle { type: "circle"; }
interface Rectangle { type: "rectangle"; }
type ShapeTemplate = {
type: Shape["type"];
};
const fromTemplate = (template: ShapeTemplate): Shape => template;
Run Code Online (Sandbox Code Playgroud)
它打破了:
TS2322: Type 'ShapeTemplate' is not assignable to type 'Shape'. Type 'ShapeTemplate' is not assignable to type 'Rectangle'. Types of property 'type' are incompatible. Type '"circle" | "rectangle"' is not assignable to type '"rectangle"'. Type '"circle"' is not assignable to type '"rectangle"'.
简而言之,对于 TypeScript 编译器来说,它通常过于复杂,无法简化{x: A} | {x: B}为{x: A|B}.
您可以在Microsoft/TypeScript#7553 的讨论以及我现在找不到的其他一些地方阅读有关此内容的内容。(编辑:另请参阅Microsoft/TypeScript#18230。)我认为该语言的维护者认为不值得尝试实现这一点,因为大多数时候它在实践中没有用;人们真正使用的类型通常具有多个属性,并且一旦您拥有{x: A, y: P } | {x: B, y: Q},则减少到类似的属性{x: A|B, y: P|Q}是无效的。
实际上,这里的解决方法是断言 aShapeTemplate可分配给Shape,如下所示:
const fromTemplate = (template: ShapeTemplate): Shape => template as Shape;
Run Code Online (Sandbox Code Playgroud)
希望有帮助;祝你好运!
| 归档时间: |
|
| 查看次数: |
186 次 |
| 最近记录: |