I have got the following interface.
export interface Student {
id: number;
name: string;
}
Besides that there is a component that holds an array of the type Student.
@Component({
selector: 'app-students',
templateUrl: './students.component.html',
styleUrls: ['./students.component.css']
})
export class StudentsComponent implements OnInit {
columnsToDisplay = ['name', 'status'];
students: Student[] = [];
constructor(private studentService: StudentService) { }
ngOnInit(): void {
}
add(name: string): void {
name = name.trim();
if (!name) { return; }
this.studentService.addStudent({ name } as Student)
.subscribe(student => {
this.students.push(student);
});
}
}
In de studentService addStudent is defined as.
@Injectable({
providedIn: 'root'
})
export class StudentService {
private studentsUrl = 'api/students'; // URL to web api
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(private http: HttpClient) { }
addStudent(student: Student): Observable<Student> {
return this.http.post<Student>(this.studentsUrl, student, this.httpOptions);
}
}
When I would like to add a field to the interface like.
export interface Student {
id: number;
name: string;
status: string;
}
How would I need to change the add function in the component? What I tried is the following.
add(name: string): void {
name = name.trim();
if (!name) { return; }
let newStudent = {
'name': name,
'status': 'testStatus'
}
this.studentService.addStudent({ newStudent } as Student)
.subscribe(student => {
this.students.push(student);
});
}
However this throws a warning in visual studio code.
Conversion of type '{ newStudent: { name: string; status: string; }; }' to type 'Student' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Type '{ newStudent: { name: string; status: string; }; }' is missing the following properties from type 'Student': id, name, statusts(2352)