If I have 2 interfaces:
interface Person{
name: string;
}
interface Employee extends Person{
employeeId: string;
}
and I want to convert a Person to en Employee:
function employPerson(person: Person, id: string): Employee
What is the best approach?
I think that the standard way of doing this is:
function employPerson(person: Person, id: string): Employee{
const employee = person as Employee
employee.employeeId = id;
return employee;
}
which works but this also works:
function employPerson(person: Person, id: string): Employee{
const employee = person as Employee
return employee;
}
which is obviously not right.
I like this approach:
function employPerson(person: Person, id: string): Employee{
return {
...person,
employeeId: id
};
}
This ensures that we have all the correct properties and if I change the Employee interface to add a new property the above code will correctly error. The problem with this is that I am returning a different object - it's a clone.
How do I add a property to an existing object whilst still using full type safety?
Thanks