使用查找类型时,Typescript TS2322错误

时间:2017-12-05 16:59:52

标签: typescript

我绞尽脑汁为什么以下代码无法编译:

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"'.

它打破了:

<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/pure/1.0.0/grids-responsive-min.css" media="all" /> </head> <body> <div id="category-desc-grid" class="pure-g"> <div class="pure-u"> <p class="title"></p> <p class="details"> Throw Style &amp; Fitted Style<br> 71 Fabric Color Choices<br> Fire resistant. Passes NFPA 701-2010<br> Full Color Dye Sublimation </p> <a href="#" class="button">Buy/View 24 Hour Tablecloths</a> </div> <div class="pure-u-1-2"> <p class="title">Single Color Front Panel, Fitted Table Colors &amp; Throws</p> <p class="details"> 4ft, 5ft, 6ft, 8ft<br> 74 Fabric Color Choices,<br> including neon colors.<br> Fire resistant. Passes<br> NFPA 701-2010 </p> <a href="#" class="button">Available in 1, 2, or 3 Day Production</a> </div> <div class="pure-u-1-2"> <p class="title">Full Color Print Front Panel</p> <p class="details"> Additional Panel Print $99<br> Fitted &amp; Throw Style<br> 4ft, 5ft, 6ft, 8ft<br> 71 Fabric Choices<br> F.R. - NFPA 701-2010 </p> <a href="#" class="button">Available in 1, 2, or 3 Day Production</a> </div> </div> </body> </html>

1 个答案:

答案 0 :(得分:3)

简短的回答是,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}的缩减就无效。

在实践中,此处的解决方法是断言ShapeTemplate可分配给Shape,如下所示:

const fromTemplate = (template: ShapeTemplate): Shape => template as Shape;

希望有所帮助;祝你好运!