在打字稿Angular 2中创建对象的实例

时间:2018-10-09 16:39:32

标签: javascript angular typescript

如何在TypeScript中创建新实例。显然我没有匹配构造函数,但看不到出了什么问题。

export class User implements IUser {
    public id: number;
    public username: string;
    public firstname: string;
    public lastname: string;
    public birthday: string;
    public email: string;

    public constructor(iUser: IUser)
    {
        this.id = iUser.id;
        this.username = iUser.username;
        this.firstname = iUser.firstname;
        this.lastname = iUser.lastname;
        this.birthday = iUser.birthday;
        this.email = iUser.email;
    }
}

    interface IUser {
        id?: number;
        username: string;
        firstname: string;
        lastname: string;
        birthday: string;
        email: string;
    }

和扩展用户的学生班级

export class Student extends User implements IStudent, IUser {
    public indeks: string;
    public studyProgram: StudyProgram;


    public constructor(iUser: IUser, iStudent: IStudent)
    {
        super(iUser);
        this.indeks = iStudent.indeks;
        this.studyProgram = iStudent.studyProgram;
    }
}

    interface IStudent {
        indeks: string;
        studyProgram: StudyProgram;
    }

因此,当我尝试创建学生的新实例时,出现此错误

 Supplied parameters do not match any signature of call target.

     this.student = new Student ({
      username: '',
      firstname: '',
      lastname: '',
      birthday: '',
      email: '',
      indeks: '',
      studyProgram: new StudyProgram({
        name: '',
        duration: 0,
        courseType: ''
    })
  });

这是StudyProgram

export class StudyProgram implements StudyProgramInterface {
        public id: number;
        public name: string;
        public duration: number;
        public courseType: string;
        public studentList: Array<Student>;

    public constructor(studyProgramCfg: StudyProgramInterface) {
        this.id = studyProgramCfg.id;
        this.name = studyProgramCfg.name;
        this.duration = studyProgramCfg.duration;
        this.courseType = studyProgramCfg.courseType;
    }
}

    interface StudyProgramInterface {
        id?: number;
        name: string;
        duration: number;
        courseType: string;
    }

1 个答案:

答案 0 :(得分:0)

Student类的构造函数期望两个对象(一个实现IStudent,另一个实现IUser),您只传递了一个。我认为您正在寻找的构造函数是:

public constructor(student: IUser & IStudent) {
    super(student);
    this.indeks = student.indeks;
    this.studyProgram = student.studyProgram;
}

您可以在此处找到有关交叉点类型的更多信息:https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html