【问题标题】:Typescript - Parameter 'u' implicitly has an 'any' type打字稿 - 参数'u'隐式具有'any'类型
【发布时间】:2016-07-05 07:12:16
【问题描述】:

我将此代码转换为最新的 Angular 2。authentication.service.ts

代码应该是什么样的?

app/auth/auth.service.ts(30,40): error TS7006: Parameter 'u' implicitly has an 'any' type.

// services/auth.service.ts
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';

//http://4dev.tech/2016/03/login-screen-and-authentication-with-angular2/
//https://github.com/leonardohjines/angular2-login
export class User {
  constructor(
    public email: string,
    public password: string) { }
}

var users:any = [
  new User('admin@admin.com','adm9'),
  new User('user1@gmail.com','a23')
];

@Injectable()
export class AuthenticationService {

  constructor(
    private _router: Router){}

  logout() {
    localStorage.removeItem("user");
    this._router.navigate(['Login']);
  }

  login(user:any){
    var authenticatedUser = users.find(u => u.email === user.email);
    if (authenticatedUser){
      localStorage.setItem("user", authenticatedUser);
      this._router.navigate(['Home']);      
      return true;
    }
    return false;

  }

   checkCredentials( ){
    if (localStorage.getItem("user") === null){
        this._router.navigate(['Login']);
    }
  } 
}

【问题讨论】:

  • 你看到这个错误的修复了吗?

标签: typescript angular


【解决方案1】:

考虑使用 (u: any) => ...

【讨论】:

    【解决方案2】:

    您可以尝试使用User 类型而不是any

    var users:User[] = [
      (...)
    ];
    

    var authenticatedUser = users.find((u:User) => u.email === user.email);
    

    【讨论】:

      【解决方案3】:

      问题的原因是没有正确定义的参数,因为这种情况是示例后面的变量“u”:

      var authenticatedUser = users.find(u => u.email === user.email);
      

      如果您没有服务的类模型,应将“u”定义为字符串或其他您需要的类型:

      var authenticatedUser = users.find(u:string => u.email === user.email);
      

      【讨论】:

        【解决方案4】:

        我正在使用您使用的相同示例。

        不应用任何,而是将参数类型设置为User

        所以,你的登录方法应该是这样的:

        login(user: User): boolean { ...

        然后,删除对 any 关键字的所有引用。

        【讨论】:

          【解决方案5】:

          要进行的 2 处更改:

          • tsconfig.json 文件中:"noImplicitAny": false,

          • systemjs.config.js,添加:

            'ng2-formly': 'npm:ng2-formly/bundles/ng2-formly.umd.js',

          【讨论】:

          • tsconfig.json 中的"noImplicitAny": false 刚刚救了我!
          猜你喜欢
          • 2021-03-29
          • 2018-09-23
          • 2018-09-25
          • 2017-11-30
          • 2017-08-21
          • 2018-11-30
          • 2021-12-24
          • 2021-05-31
          • 2019-03-15
          相关资源
          最近更新 更多