#Safely adding a property to move from one Type to another Type

3 messages · Page 1 of 1 (latest)

leaden sorrel
#

I have Person, Address and PersonWithAddress types (a person with an an address property of type Address)

I am trying to come up with a Type-safe way to move from a Person to a PersonWithAddress once the relevant property has been set, so my function can then return a PersonWithAddress that is guaranteed to have an address.

Is there any way of achieving this in a Type-safe way?

type Person = { name: string };
type PersonWithAddress = Person & { address: Address };
type Address = { text: string };

function getPersonWithAddress(): PersonWithAddress {
  const person: Person = { name: 'Bob' };
  const address: Address = { text: "Somewhere" };
  person.address = address;
  return person;
}```
sly tusk
#

Simply do:

return { ...person, address }
leaden sorrel
#

I was clearly missing the obvious there - thank you so much! 🙂