Zhu
Zhu

Reputation: 3895

type 'X' is not assignable to type 'Y' in angular 4

I am sorry for asking this question ,but I need someone's help to fix it .

What I trying is I have a model class in my Angular 4 app,I want to assign the type to a property in component but it shows the error as

error :

[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 (model class)

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

component

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 {
  }
}

here mUser is underlined as red and showing the above error .

can anyone help me to fix this issue .

Upvotes: 2

Views: 708

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68655

At the initialization stage you assign to mDOB property the function with name Date (so why error is about Type 'DateConstructor' is not assignable to type 'Date'.), not it's instance. Either assign a default date or 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,
  };

Upvotes: 1

Related Questions