Home > front end >  Element implicitly has an 'any' type because expression of type '"status"&#
Element implicitly has an 'any' type because expression of type '"status"&#

Time:03-09

Unable to index "res" with a string. I've tried other fixes i found but the context that it is used here in my code it does not recognise the object being defined earlier.

full error : "Element implicitly has an 'any' type because expression of type '"status"' can't be used to index type 'Object'. Property 'status' does not exist on type 'Object'.ts(7053)"

error here:

if(res['status'] === 'success')

full function:

export class LoginComponent implements OnInit {
    public user : User;
    
    
    constructor(private loginService: LoginService, private router: Router) {
        this.user = new User();
    }
    
    validateLogin() {
        if(this.user.username && this.user.password) {
            this.loginService.validateLogin(this.user).subscribe(res => {
                console.log('result is ', res);
                if(res['status'] === 'success') {
                    this.router.navigate(['/home']);
                } else {
                    alert('Wrong username password');
                }
            }, error => {
                console.log('error is ', error);
            });
        } else {
            alert('enter user name and password');
        }
    }
    
    ngOnInit(): void {
    }
    
}

CodePudding user response:

you can try to note typescript that res is just a type, that can have status field, it may help

 if((res as {[key: string]: any})['status'] === 'success') {
    this.router.navigate(['/home']);
 } else {
    alert('Wrong username password');
 }

  • Related