React Native Typescript. Non working type check

Viewed 1519

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 Answers

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

Related