Programming Environment: Angular 6
export class Student {
fullName: string;
age: number;
classType: string;
}
export class MyClass {
public resultData: Array<Student> = [];
processedData = {
studentData: [
{
name: 'Nayan',
type: 'toddler',
classType: 'secondary'
},
{
name: 'Rajesh',
type: 'infant',
classType: 'primary'
},
{
name: 'Rithik',
type: 'toddler',
classType: 'secondary'
},
{
name: 'Rob',
type: 'toddler',
classType: 'primary'
},
{
name: 'Daniel',
type: 'toddler',
classType: 'secondary'
}
]
}
resultData1 =[
{name:'nayan', age:8, classType:'primary'},
{name:'Daniel', age:15, classType:'secondary'},
{name:'Rithik', age:12, classType:'secondary'}
]
someEventClickedFormView() {
this.processedData.studentData.forEach((data, index) => {
switch (data.classType) {
case 'primary': {
this.processName(data, 'fullName', index);
this.processAge(data,'age',index);
break;
}
case 'secondary': {
this.processName(data, 'fullName', index);
this.processAge(data,'age',index);
break;
}
}
})
}
public processName(data: any, fieldName: string, index: number) {
this.resultData.push({ fieldName: data.fullName })
// Error occurs here
}
public processAge(data:any,fieldName:string,index:number) {
this.resultData.push({ fieldName: this.someTransformationToAge(data.age)})
}
}
A button click event triggers the someEventClickedFormView()
function which populates the resultData
array with mock data.
An error message is displayed related to the push method in the code snippet above.
Error Message: Argument of type '{ fieldName: any; }' is not assignable to parameter of type 'Student'. Object literal may only specify known properties, and 'fieldName' does not exist in type 'Student'.ts(2345)
The desired format for the resultData
array should be as shown below:
resultData =[
{name:'nayan', age:8, classType:'primary'},
{name:'Daniel', age:15, classType:'secondary'},
{name:'Rithik', age:12, classType:'secondary'}
]