如何在 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;
}
最佳答案
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
关于javascript - 在 typescript Angular 2中创建对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52725660/