首页 > 解决方案 > 类型“X”不能分配给角度 4 中的类型“Y”

问题描述

很抱歉提出这个问题,但我需要有人帮助解决它。

我尝试的是我的 Angular 4 应用程序中有一个模型类,我想将类型分配给组件中的一个属性,但它显示错误为

错误 :

[ts]
Type '{ gender: null; mTitle: null; mFName: null; mLName: null; mEmail: null; mPassword: null; mDOB: Da...' is not assignable to type 'User'.
  Types of property 'mDOB' are incompatible.
    Type 'DateConstructor' is not assignable to type 'Date'.
      Property 'toDateString' is missing in type 'DateConstructor'.
(property) CreateaccountComponent.mUser: User

User.ts(模型类)

export class User {
    gender :string;
    mTitle: string;
    mFName: string;
    mLName: string;
    mEmail: string;
    mPassword: string;
    mDOB: Date;
    mNewsLetter: string;
    mSpecialOffer: string;
}

零件

import { User } from '../../User';

export class CreateaccountComponent implements OnInit {

  mUser: User = {
    gender: null,
    mTitle: null,
    mFName: null,
    mLName: null,
    mEmail: null,
    mPassword: null,
    mDOB: Date,
    mNewsLetter: null,
    mSpecialOffer: null,
  };

  constructor(private CartdataService: CartdataService, private router: Router, private http: HttpClient, ) {
    this.router.events.subscribe(() => window.scrollTo(0, 0));
  }

  ngOnInit() { }
  submitForm(userForm: NgForm): void {
  }
}

这里 mUser 下划线为红色并显示上述错误。

谁能帮我解决这个问题。

标签: angulartypescript

解决方案


在初始化阶段,您将mDOB具有名称的函数分配给属性Date(所以为什么错误是关于Type 'DateConstructor' is not assignable to type 'Date'.),而不是实例。指定默认日期或null.

mUser: User = {
    gender: null,
    mTitle: null,
    mFName: null,
    mLName: null,
    mEmail: null,
    mPassword: null,
    mDOB: new Date, // <----- new Date or null
    mNewsLetter: null,
    mSpecialOffer: null,
  };

推荐阅读