想象一下我有2个html表彼此相邻。每个表都有一系列未分配的学生或指定的学生进行某项测试。使用2个按钮,您可以将复选框选中的瞳孔移动到另一个html表格。
两个html表中的学生都具有几乎相同的属性。
当我使用Object.Assign时,我收到编译错误:
properties gradeScorePairs is missing in type {} and UnAssignedPupil
要解决该错误,我只需在两个对象上复制/粘贴相同的属性......
这是一种解决方法,但对我来说不是解决方案。我使用Typescript 2并转换为ES5。
我有什么方法可以使用object.assign和源/目标的不同类型来解决这个问题?
AssignedPupil.ts
import { GradeScorePair } from './gradeScorePair';
export class AssignedPupil {
constructor(obj: any) {
this.id = obj.id;
this.name = obj.firstName + " " + obj.lastName;
}
id: number;
name: string;
gradeScorePairs: GradeScorePair[];
isSelected: boolean;
selectedGradeScorePair: GradeScorePair;
}
UnAssignedPupil.ts
import { GradeScorePair } from './gradeScorePair';
export class UnAssignedPupil {
constructor(obj: any) {
this.id = obj.id;
this.name = obj.firstName + " " + obj.lastName;
}
id: number;
name: string;
// gradeScorePairs: GradeScorePair[]; // don`t need it on the unassigned html table
isSelected: boolean;
// selectedGradeScorePair: GradeScorePair; // don`t nee it on the unassigned html table
}
unassignPupil() {
var i = this.assignedPupils.length;
while (i--) {
var p = this.assignedPupils[i];
if (p.isSelected) {
let assignedPupil: AssignedPupil = this.assignedPupils.splice(i, 1)[0];
let unAssignedPupil: UnAssignedPupil = Object.assign({}, assignedPupil);
unAssignedPupil.isSelected = false;
this.unAssignedPupils.push(unAssignedPupil);
}
}
}
assignPupil() {
var i = this.unAssignedPupils.length;
while (i--) {
var p = this.unAssignedPupils[i];
if (p.isSelected) {
let pupilToAssign: UnAssignedPupil = this.unAssignedPupils.splice(i, 1)[0];
let assignedPupil: AssignedPupil = Object.assign({}, pupilToAssign);
// Difference are these 2 lines of code
assignedPupil.gradeScorePairs = this.gradeScorePairs;
assignedPupil.selectedGradeScorePair = null;
assignedPupil.isSelected = false;
this.assignedPupils.push(assignedPupil);
}
}
}
答案 0 :(得分:1)
您可以告诉编译器此空对象的类型为AssignedPupil
:
let assignedPupil: AssignedPupil = Object.assign({} as AssignedPupil, pupilToAssign);
这将清除错误。
问题是,当你这样做时,你真的没有一个类AssignedPupil
的实例,你就会拥有一个具有相同属性的对象。
由于打字稿的duck typing性质,您不会有错误。
如果你打算只使用该类作为数据对象,那么你很好(但为什么不只是使用接口?),但如果你打算使用类方法,那么变量assignedPupil
赢了&# 39;没有那些。
一个例子:
class Point {
constructor(public x: number, public y: number) { }
distance(other: Point) {
return Math.sqrt(Math.pow((this.x - other.x), 2) + Math.pow((this.y - other.y), 2));
}
toString() {
return `(${this.x}, ${this.y})`;
}
}
let a1 = new Point(0, 0);
console.log(a1.x); // 0
console.log(a1); // Point {x: 0, y: 0}
console.log(a1.toString()); // (0, 0)
let a2 = Object.assign({} as Point, a1);
console.log(a2.x); // 0
console.log(a2); // Object {x: 0, y: 0}
console.log(a2.toString()); // [object Object]
console.log(a1.distance(a2)); // 0
console.log(a2.distance(a1)); // Uncaught TypeError: a2.distance is not a function