【问题标题】:Angular strictTemplates union typesAngular strictTemplates 联合类型
【发布时间】:2021-07-04 12:28:59
【问题描述】:

我正在使用带有 DevExtreme UI 框架的 Angular 11 (11.2.14)。打字稿版本是 4.0.7。我已经启用了 strictTemplates,现在我在生产中编译时遇到了这个错误:

Error: src/app/views/product/product.component.html:11:45 - error TS2322: Type 'string | number | Date' is not assignable to type 'Date'.
  Type 'string' is not assignable to type 'Date'.

11                     <dx-date-box [(value)]="endDate"
                                               ~~~~~~~~
12                                  type="date"
   ~~~~

EndDate 在组件中定义:

endDate: Date;

我无法理解真正的问题,因为 DevExtreme 类型定义正确:

/**
* An object or a value specifying the date and time currently selected using the date box.
*/
value?: Date | number | string;

联合类型似乎有问题。

【问题讨论】:

  • 也许这是因为双向绑定。相当于:const out: string = (value as Date | number | string)
  • 启用 strictNullChecks 后,当值为 null 或未定义时,您需要在对该值使用方法或属性之前测试这些值。
  • @AlexanderAlexandrov,谢谢,你是对的,这是因为双向绑定。有什么解决方法吗?
  • @PsyGik,目前我们没有启用strictNullChecks

标签: javascript angular typescript devextreme


【解决方案1】:

由于声誉不足,无法添加评论...但要回答:

thx,你是对的,这是因为双向绑定。有没有 解决方法?

是的,当然。

您可以创建一个计算属性(get 和 set),其中 setter 接受所有三种类型,然后在内部执行类型检查以验证它实际上是 Date 类型,然后在其中设置 endDate 属性。

【讨论】:

    猜你喜欢
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2020-08-04
    • 1970-01-01
    • 2018-07-29
    • 2019-01-12
    • 1970-01-01
    相关资源
    最近更新 更多