One of the functions I have implemented is designed to remove null values from an array that is passed as input. This function also provides an optional transform functionality, allowing the user to modify the elements of the array into a custom format if needed. Here is the code:
export const getValidItems = <TItem, TReturn>(
items: Maybe<TItem>[],
transform?: (item: TItem) => TReturn
) => {
const validItems: (TItem | TReturn)[] = [];
items.forEach((item) => {
if (item) {
const outputItem = transform ? transform(item) : item;
if (outputItem) {
validItems.push(outputItem);
}
}
});
return validItems;
};
This is how I am using the above function:
const nodes = getValidItems(edges, ({ node }) => node);
Although I have included checks for non-null values in the `getValidItems` function, TypeScript still raises a warning when I attempt to iterate over the `nodes` variable, indicating a possible presence of 'null' or 'undefined' objects.
Prior to consolidating this logic into a helper function, it was part of another method where TypeScript correctly recognized non-null values based on the `if (item)` and `if (outputItem)` checks within that method. However, upon transitioning to the `getValidItems` helper, these errors began surfacing.
For additional context, here is the original function before refactoring:
export const getNodes = <TNode>(data?: { edges?: { node?: TNode | null }[] | null }) => {
const { edges } = data || {};
if (!edges) {
return [];
}
const validNodes: TNode[] = [];
edges.forEach(({ node }) => {
if (node) {
validNodes.push(node);
}
});
return validNodes;
};
And below is the function post-refactoring with the introduction of the helper:
export const getNodes = <TNode>(data?: { edges?: { node?: TNode | null }[] | null }) => {
const { edges } = data || {};
if (!edges) {
return [];
}
const nodes = getValidItems(edges, ({ node }) => node);
return nodes
};
Upon revisiting the updated `getNodes`, TypeScript struggles to infer that `nodes` should be `(typeof node)[]` and that there are no null values within the array elements. Is there a way to assert that the output from my function does not contain null or undefined entries? Alternatively, is there a different approach to writing the function that allows TypeScript to accurately define both the information and return type of `transform`?