Best practice way to transition from one type to another in Typescript

If I have 2 interfaces:

interface Person{
    name: string;
}

interface Employee extends Person{
    employeeId: string;
}

      

and I want to convert Person to en Employee:

function employPerson(person: Person, id: string): Employee

      

What's the best approach?

I think the standard way to do it is:

function employPerson(person: Person, id: string): Employee{
    const employee = person as Employee

    employee.employeeId = id;

    return employee;
}

      

but this also works:

function employPerson(person: Person, id: string): Employee{
    const employee = person as Employee

    return employee;
}

      

which is obviously not true.

I like this approach:

function employPerson(person: Person, id: string): Employee{
    return {
        ...person,
        employeeId: id
    };
}

      

This will ensure that we have all the correct properties, and if I change the interface Employee

to add a new property, the above code is correctly incorrect. The problem is I am returning another object - this is a clone.

How do I add a property to an existing object while maintaining full type safety?

thank

+3


source to share


1 answer


How about Object.assign

?



function employPerson(person: Person, id: string): Employee {
    return Object.assign(person, {
        employeeId: id
    });
}

      

+1


source







All Articles