Iwa Greenwood
Iwa Greenwood

Reputation: 35

Property doesn't exist on type

I'm facing a strange problem. so my function authenticateUser returns and array like this

{
  success: false,
  msg: "invalid password"
}

But when I'm trying to check if the success == false I get the error that there is no such property on type Objects

 this.authService.authenticateUser(user).subscribe(data=>{
  if(data.success){//here need to check response for success
    console.log(data)
    this.authService.storeUserData(data);
    this.router.navigate(['/user']);
  }else{
    this.router.navigate(['/login']);
  }

I've tried to use examples from other tutorials, but still no solution

Upvotes: 2

Views: 135

Answers (2)

penleychan
penleychan

Reputation: 5470

You have 2 ways to do this:

Option 1 use type any:

this.authService.authenticateUser(user).subscribe((data: any)=>{
  if(data.success){//here need to check response for success
    console.log(data)
    this.authService.storeUserData(data);
    this.router.navigate(['/user']);
  }else{
    this.router.navigate(['/login']);
  }
}

Or doing it strongly typed {success: boolean, msg: string} or create a interface of this type:

this.authService.authenticateUser(user).subscribe((data: {success: boolean, msg: string}) =>{
  if(data.success){//here need to check response for success
    console.log(data)
    this.authService.storeUserData(data);
    this.router.navigate(['/user']);
  }else{
    this.router.navigate(['/login']);
  }
}

Upvotes: 1

Shanon Jackson
Shanon Jackson

Reputation: 6581

Not too familiar with Angular but it's because data isn't typed properly, you can fix this by casting or by a type-guard.

const hasSuccess = (something: any): something is {success: boolean} {
     return "success" in something;
}

if(hasSuccess(data) && data.success) ...

Upvotes: 0

Related Questions