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
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.
We can use Object. assign({},object) to convert string into object.
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.
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.
How about Object.assign
?
function employPerson(person: Person, id: string): Employee {
return Object.assign(person, {
employeeId: id
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With