首页 > 解决方案 > 未定义不可分配给用户类型

问题描述

我收到以下错误

error TS2322: Type 'MyConfig| undefined' is not assignable to type 'MyConfig'.
Type 'undefined' is not assignable to type 'MyConfig'.

从我们可以调用MyAppComponent的具有以下输入变量的组件中

  @Input() userInfoInput?: UserInfo;

  @Input() MyConfigInput?: MyConfig;

UserInfo 是下图所示的接口模型

export interface UserInfo{
   [key: string]: any;
   firstName: string | undefined;
   middleName: string | undefined;
   lastName: string | undefined;
 }

MyConfig 是一个类

export class MyConfig{
  private _name!: string;
  private _description!: string;
  private _version!: string;
  private _dateFormat!: string;
  private _maxContentLength!: number;

  constructor(
     name: string,
     description: string,
     version: string,
     dateFormat: string,
     maxContentLength: number,
     ) {
     this.name = name;
     this.description = description;
     this.version = version;
     this.dateFormat = dateFormat;
     this.maxContentLength = maxContentLength;
   }

在当前的功能代码中,@Input变量用非空断言运算符修饰,!因为我无法在构造函数中显式定义它们。我想改用?/ MyConfigInput : MyConfig | undefined,但我收到了无法将 undefined 分配给这些类型的错误。我已经提供了我在@Input这个组件中创建的其他类型进行测试,它们没有报告相同的错误。所以我想我错过了一些关于为什么我不能undefined特别分配给这些类型的直觉。

任何对此问题的见解将不胜感激!

标签: angulartypescriptangular7

解决方案


推荐阅读