Validating react navigation with Type Script Generics
if (this.navigation.state.params && this.navigation.state.params.name)
Are you writing similar code to validate your navigation params to avoid a run time crash in the react native application?
Very well . certainly there is better way to validate it during the compilation time. The answer is TypeScript using generics.
- Lets write a StandardNavigation.ts class with some generics codes
2. Home.tsx file: initialRoute
Here I define ‘name’ is the only navigation parameter i would be passing to the details screen.
Compilation error:
Since HomeNavigationParams interface has ‘name’ only property, it will not allow(compilation error) any other parameters unless we declare them in the interface.
3. Details.tsx file
In the Details screen only HomeNavigationParams parameters are available to get (this.props.navigation.state.params.name).
In old javascript code if you missed types the params , app will crash silently.But with typescript we can actually avoid those runtime failure/ crash.
Compilation error:
HomeNavigationParams interface doesn’t have property ‘nmae’.
Conclusion: It’s better to fix the compilation errors than app crashes.
Sample project :