angular - 未定义不可分配给用户类型
问题描述
我收到以下错误
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
特别分配给这些类型的直觉。
任何对此问题的见解将不胜感激!
解决方案
推荐阅读
- php - PHP:将数组转换为索引数组
- database - MS Access 表单只读
- vue.js - GSAP 无法使用 vue Nuxt.js 导入模块
- linear-programming - ZIMPL:约束中无法识别二维变量声明
- biginteger - 在java中将反转数组转换为java.math.Biginteger
- python - Pandas `to_csv` 字符串列已转换
- python - 在python中逐行合并几个文本文件
- php - Wordpress 子主题 style.css 已停止工作
- javascript - 用你的键盘用javascript点亮一个盒子
- c++ - 使用分隔符从文件中分配变量