2
votes

I'm working on RN with Typescript. By using the official instruction I was managed to add .tsx and .ts file but the main problem I faced is that RN doesn't detect the incorrect types in the files at all. For ex.

At the beginning of App.tsx I added the wrong TS statement.

let a: number = 5;
a = "test"

When I added it to the standard React app (for web) the TS compiler shows me

Type '"test"' is not assignable to type 'number'. TS2322

But when I did the same in the case of RN, it just compiles and didn't show any warnings/errors, etc. The app is simply started on the emulator like everything is fine.

It's the first time when I'm trying to use RN with Typescript. Before I used only WEB apps + typescript so that why I'm wondering is such behavior correct? How can I enable the type-checking in the case of React native?

P.S. I even tried this one. The same behavior.

Thanks for any help.

1
What is your RN version? I will try to replicate - Muni Kumar Gundu
Hi Muni. Thanks for the answer. I'm using: "0.61.5" - Velidan
not a direct solution, but if you continue having issues you can enable TS type checking in your editor (VS Code should work out of the box if it detects a tsconfig) and add ESLint with the TypeScript extension to lint your project before the build starts (as a part of the build/start script) so that you get all the errors and warnings that way - 5ar
Hi 5ar. Thanks for the suggestion. But how about the ts issues when you are developing while the server is running? I think it's just a workaround. I'd like to understand why TS doesn't work in general - Velidan

1 Answers

4
votes

I spent almost the whole day to find a solution and it looks like the RN typescript template doesn't support type checking out of the box. Regarding their official documentation use tsc command to check types it means we usually should check types only before committing, etc. (could be done via some pre-commit hooks like husky)

But as we can use tsc so we can use watchMode as well

I used a workaround by adding the script into my package.json to run the tsc into watch mode and I run it in parallel with the standard react-native command to have the runtime type checking.

// package.json
"scripts": {
    "android:ts-watch": "concurrently \"yarn check-types:watch\"  \"react-native run-android\"",
    "check-types": "tsc",
    "check-types:watch": "tsc --watch"
 }

Warning. You need to install concurrently package if you want copy-paste this script.

P.S. Unfortunately the error warnings in the console don't have colors (red, etc.) so it could be pesky, but anyway it's much better than to not have type checking at the runtime at all.

If someone finds a bit more correct way, please, let me know