'Evolution of an objects properties using TypeScript

I have the situation in which I have a domain entity which can be in a "just born" state and then more mature state, once more data is fetched from a 3rd party.

A simple example would be:

interface Props {
  name: string;
  idFrom3pAPI?: string;
}

When a request arrives to my system I would like to create the domain object, but some data will be missing, I will then pass this object to a service/repo which will obtain the missing keys and return the complete object.

The issue with the above type is that when I try to pass this object to the ORM it will not type check as idFrom3pAPI cannot be undefined.

So essentially I am looking for a conditional or discriminated union type, where I could set a flag on the objects state, and the type checker would be happy that it now has the correct data.

Any help appreciated!



Solution 1:[1]

I may not be reading your question correctly, however I agree with your initial attempt where idFrom3pAPI is optional if it in fact may or may not exist. However, if your ORM cannot accept idFrom3pAPI being an optional, then this solution should work.

First, remove the optional from idFrom3API

interface Props {
  name: string;
  idFrom3pAPI: string;
}

Then you can use the Partial utility type when you pass it to the "service/repo" and that "service/repo" would return the full type. The "service/repo" should accept Partial and return Props. The variable that receives the initial request would be Partial<Props> and a new variable of type Props would receive the result from your "service/repo"

Then your ORM can accept Props as defined above without the optional.

Another option would be to create a different type and later narrow it to the type the ORM wants.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1