错误 TS2322:输入“字符串 |”数量 |在刚刚升级到 Angular 16 的项目上,无法分配“日期”来键入“日期”

问题描述 投票:0回答:1

我有一个刚刚从 Angular 11 升级到 Angular 16 的项目。在 Angular 11 中,我使用 Web API 的 Swagger JSON 文件中的 NPM 包“ng-swagger-gen”创建了所有 DTO 模型。 “ng-swagger-gen”正在 TypeScript DTO 模型中为我的 C# 类中的 DateTime 字段生成一个字符串成员,该类是 Web API 的一部分。

我有一个名为 Action 的实体的 DTO 类。在我的 C# 类中,在 Web API 端,操作的开始时间被声明为可为空的 DateTime 属性字段:

[DataMember] public DateTime? actionStartDate { get; set; }

“ng-swagger-gen”在我的 Angular 项目中创建的 TypeScript 模型中生成一个可选字段:

actionStartDate?: string;

在我的 HTML 中,我有一个弹出窗口表单,我可以在其中更新操作。对于操作的开始日期,我使用 DevExtreme API 中的 DateBox 小部件:

<dx-date-box type="date"
                    displayFormat="shortdate"
                    [(value)]="updateAction.actionStartDate"
                    [min]="today">
                    <!-- [displayFormat]="{type: 'MM/dd/yyyy'}" -->
         <dx-validator>
           <dxi-validation-rule type="required" message="The action's start date is a required field"></dxi-validation-rule>
         </dx-validator>
       </dx-date-box>

整个方法在 Angular 11 中运行得非常好,但是现在,当我升级到 Angular 16 时,当我尝试编译项目时遇到错误(“ng build”):

error TS2322: Type 'string | number | Date' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.

28 [(value)]="updateAction.actionStartDate"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
29 [min]="today">

有趣的是,Visual Studio Code 不会标记该错误(在小部件的值与要更新的操作的 actionStartDate 字段的绑定下方没有红色波浪线:

让我更加困惑的是,我还有其他情况,其中组件中的绑定变量实际上被定义为“日期”,但我仍然遇到相同的错误。

为什么会出现这种情况,解决办法是什么?

谢谢, 艾迪

typescript angular11 angular16 devextreme-angular
1个回答
0
投票

事实证明,可以通过关闭 tsconfig.json 文件内“angularCompilerOptions”部分中的“strictTemplates”标志来解决这个问题,如下所示:

"angularCompilerOptions": {
   "enableI18nLegacyMessageIdFormat": false,
   "strictInjectionParameters": true,
   "strictInputAccessModifiers": true,
   "strictTemplates": false
 }

另一种方法是保持 strictTemplates 标志打开,并将绑定到 dx-date-box 控件值的所有变量声明为“string | number | Date”。这对我不起作用,因为每次我使用 ng-swagger-gen 刷新 DTO 模型时,这些类型都会被覆盖。

© www.soinside.com 2019 - 2024. All rights reserved.