Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice way of converting from one type to another in Typescript

Tags:

typescript

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

like image 704
Roaders Avatar asked Aug 04 '17 08:08

Roaders


People also ask

How do I cast a data type in TypeScript?

Type Casting a string type to a number using 'as'log('The length of the string is: ', stringLength) ; 'Flower' and 'stringLength' are initialized in string and number types, respectively, in this code. Using the typecasting approach, the length of the string inside the variable flower is stored in the variable length.

How do I cast a string to an object in TypeScript?

We can use Object. assign({},object) to convert string into object.

How do you change from one type to another in TypeScript?

JavaScript doesn't have a concept of type casting because variables have dynamic types. However, every variable in TypeScript has a type. Type castings allow you to convert a variable from one type to another. In TypeScript, you can use the as keyword or <> operator for type castings.

How do you change a type to a string in TypeScript?

toString() method to convert data any type to a string. we will first create any type variable with sample array data and then we will check their data type. after that we will use the . toString() method to convert it into a string.


1 Answers

How about Object.assign?

function employPerson(person: Person, id: string): Employee {
    return Object.assign(person, {
        employeeId: id
    });
}
like image 85
Rodris Avatar answered Oct 04 '22 05:10

Rodris