In a typical scenario, the process involves creating an empty object and populating it with the necessary data. Initially, this object does not contain any properties, which leads to TypeScript flagging an error since it lacks the required type.
For instance:
interface ISomeType {
x: string;
y: string;
}
function buildObj(): ISomeType {
const obj: ISomeType = {}; // TS Error: {} doesn't include x and y
obj.x = foo();
obj.y = bar(); // Once filled, the object is correct
return obj;
}
How can I address this issue? How do I communicate to TypeScript that the new object should adhere to the specified type, even though it currently lacks the necessary properties but will have them by the end of the process?
If I designate obj
as Partial<ISomeType>
, I am unable to set the function return type as ISomeType
, which is my objective.