Flow control
Typescript Genie offers two method to append to builders conditionally. For conditions, each builder contains $if
and for mapping arrays builders contains $reduce
.
.$if(condition, isTruthy)
Method .$if
calls and returns the isTruthy
function if the condition
is truthy. This is useful for example when rendering some interface property if some data are available.
- With $if
- Without $if
const withAge = () => Math.random() > 0.5;
const interfac = tsg.statement.interface("Person")
.prop("firstname", "string")
.$if(withAge(), i => i.prop("age", "number"));
const withAge = () => Math.random() > 0.5;
let interfac = tsg.statement.interface("Person")
.prop("firstname", "string");
if(withAge()) {
interfac = i.prop("age", "number");
}
.$reduce(iterable, accumulator)
Method .$reduce
chains accumulator
calls for each item in the iterable
(e.g. array). This is useful when dealing
- With $reduce
- Without $reduce
const properties = {
firstname: "string",
age: "number"
} as const;
let interfac = tsg.statement.interface("Person")
.$reduce(Object.entries(properties), (i, [key, value]) =>
i.prop(key, value)
);
const properties = {
firstname: "string",
age: "number"
} as const;
let interfac = tsg.statement.interface("Person");
for (const [key, value] of Object.entries(properties)) {
interfac = interfac.prop(key, value);
}