Thursday, March 12, 2020

Use .filter? Sorry, no control flow analysis joy for you

function* getRoutesComponentsX(routes: Routes) {
    yield* routes
        .filter(route => route.component)
        .map(route => route.component);

    yield* routes
        .filter(route => route.children)
        .map(route => Array.from(getRoutesComponentsX(route.children!)))
        .reduce((a, b) => a.concat(b), []);
}

TypeScript won't be able to follow the flow of control when using .filter instead of if statement.

That would sometimes lead to use of non-null assertion operator.

Removing the non-null assertion operator would lead to this error:



Here's essentially same code, albeit using just if statements, no more need to use the non-null assertion operator.
function* getRoutesComponents(routes: Routes) {
    for (const route of routes) {
        if (route.component) {
            yield route.component;
        }

        if (route.children) {
            yield* getRoutesComponents(route.children);
        }
    }
}

No comments:

Post a Comment