Click here for a hands-on example. Take a look at the code snippet below:
export type BigType = {
foo: number;
bar?: number;
baz: number;
qux?: string[];
};
function BuildBigType(params: string[]) {
// Here's what I'd like to do:
const endResult: BigType = {};
//some logic for getting foo
endResult.foo = 5;
//some logic for getting bar
endResult.bar = undefined;
//...
return endResult;
}
The issue lies in the fact that {}
doesn't conform to the structure of BigType
. Two potential solutions come to mind:
Type cast
endResult
toany
and proceed with assigning the fields as demonstrated in the example.Declare local variables for each field in BigType, then assign them accordingly at the end of the function. For example:
//... return {foo, bar, baz, qux}; }
Are there any alternative approaches worth considering?