Why does TypeScript not throw a compile error for an undefined type

Viewed 965

Here's a simple repro to describe the problem:

  1. I created a vanilla RN project using npx react-native init MyApp --template react-native-template-typescript
  2. In App.tsx, I added let foo: IThoughtTheWholePointOfATypeSafeLanguageWasNotToAllowShitLikeThis = "...seriously, wtf, why does this compile without an error!?";
  3. I run the app using yarn iOS

The app runs fine and there are no errors in the bundler.

Question: How do I make it throw a compile error?

2 Answers

You can use --strict in your compiler options.

This will:

Enable all strict type checking options. Enabling --strict enables --noImplicitAny, --noImplicitThis, --alwaysStrict, --strictBindCallApply, --strictNullChecks, --strictFunctionTypes and --strictPropertyInitialization.

Source: https://www.typescriptlang.org/docs/handbook/compiler-options.html

Figured it out.

yarn tsc does the compilation and generates type errors, if there are any. You can chain this as part of other commands in your package.json file, by preceding the existing command with yarn tsc &&, if you need to fail on type errors before invoking the intended command.

For example, one of the commands in my package.json is as follows:
"test": "yarn tsc && rm -f __tests__/**/*.js && jest --coverage"

The rm bit may be helpful to you, as I've noticed that running tsc generates .js versions of all your .ts files.

Related