角度4中无法将类型“ X”分配给类型“ Y”

时间:2018-06-22 07:36:24

标签: angular typescript

很抱歉提出这个问题,但是我需要别人的帮助来解决。

我想做的是在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带有红色下划线并显示上述错误。

任何人都可以帮助我解决此问题。

1 个答案:

答案 0 :(得分:1)

在初始化阶段,您将名称为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,
  };