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:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVD8HLgSQJY5T2ymxVWaG1dBGgWQR5wzetyubm20lJKfxSHXrdZSivTTg9-fCEtCfmbBZfiPbTy_4_V13OiQiZkZk58DK3_hLF9lKAFQqnz_E0a1Btk7FS1PLDT8PLxIo2AJXyNBiUT175/s640/Screen+Shot+2020-03-12+at+10.15.21+AM.png)
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