让用户:User = new User(....)为什么这对我不起作用?

Jei*_*izi 2 typescript angular angular5

嗨,我正在尝试创建一个新用户,这个语法不起作用,它说'用户'只引用一个类型,但在这里被用作值.

 onSubmit() {
    if (this.userForm.valid) {

        let user: User = new User(null,
        this.userForm.controls['cin'].value,
        this.userForm.controls['familyName'].value,
        this.userForm.controls['givenName'].value,
        this.userForm.controls['email'].value,
        this.userForm.controls['description'].value,
        this.userForm.controls['code'].value);
        this.adminService.createUser(user).subscribe();
     }
  }
Run Code Online (Sandbox Code Playgroud)

export interface User {
  cin: string;
  givenName: string;
  familyName: string;
  role: string;
  id: string; 
  email: string;   
}
Run Code Online (Sandbox Code Playgroud)

这是因为User被声明为接口?我怎么解决它?提前致谢 :)

Tit*_*mir 5

是的,接口没有构造函数,它们只是通知编译器有关对象形状的类型,因此编译器可以检查代码并在编译时擦除.最简单的方法是给我们一个对象文字来创建一个满足接口的对象:

export interface User {
    cin: string;
    givenName: string;
    familyName: string;
    role: string;
    id: string; 
    email: string;   
}
let user: User = {
    cin: this.userForm.controls['cin'].value,
    familyName: this.userForm.controls['familyName'].value,
    givenName: this.userForm.controls['givenName'].value,
    email: this.userForm.controls['email'].value,
    id : "", // not sure where this comes from 
    role: ""  // not sure where this comes from 
}   
Run Code Online (Sandbox Code Playgroud)

您还可以创建一个实现该接口的类,但如果您没有任何方法,通常不需要这样做.您可能还需要标记某些字段为可选(例如ID,您可以使用像这样做:id?: string;)