Sub topic 1
Setting up TypeScript for TSX
This chapter configures a project so the compiler checks your React components. You will set up tsconfig.json, learn what each option does, and see the errors that appear when an option is wrong or missing.
Prerequisites
This chapter assumes you already know:
- Basic React: function components, props, state, and JSX.
- TypeScript fundamentals: interfaces, type aliases, unions, and generics.
- How to run a project with a bundler or framework such as Vite or Next.js.
You do not need to know how to type props, hooks, or events yet. Later chapters cover those.
What TSX is and who checks it
TSX is TypeScript with JSX syntax. Files that contain JSX must use the .tsx extension. A .ts file cannot contain JSX, because <Card /> would parse as a type assertion or a comparison.
Two separate tools handle a TSX file, and they do different jobs:
- The type checker (
tsc) reads your types and reports errors. It is the only tool that understands types. - The transpiler turns TSX into JavaScript the browser can run. Vite uses esbuild or SWC, Next.js uses SWC, and Babel is another option. These tools strip types without checking them.
Because of this split, your bundler will happily run code that has type errors. You get type safety only if you run the checker yourself, either with tsc --noEmit or through your editor and CI.
Install the packages
Add TypeScript and the React type definitions as development dependencies:
npm install --save-dev typescript @types/react @types/react-domReact does not ship its own types. The @types/react package supplies the types for useState, ChangeEvent, ReactNode, and the JSX namespace. Keep its major version in line with your React version. A mismatch can produce confusing errors on props such as children or ref.
Vite's react-ts template and create-next-app --typescript install these for you. If you start from a template, check that the options below are present rather than assuming.
A minimal tsconfig.json
This configuration turns on strict checking and the automatic JSX runtime:
{
"compilerOptions": {
"strict": true,
"jsx": "react-jsx",
"module": "esnext",
"moduleResolution": "bundler",
"noEmit": true
}
}The next sections explain each option.
strict
"strict": true switches on a family of checks. The ones that matter most for React are:
| Flag | What it catches in React code |
|---|---|
| `strictNullChecks` | Using `ref.current` or a nullable state value without checking for `null`. |
| `noImplicitAny` | A function parameter, such as an event handler argument, that has no type. |
| `strictFunctionTypes` | Passing a handler with an incompatible parameter type as a prop. |
| `strictPropertyInitialization` | Class fields that are never assigned. This matters little for function components. |
Without strict, TypeScript treats null as assignable to every type. The component below would then compile, even though user starts as null:
import { useState } from "react";
interface User {
name: string;
}
export function Greeting() {
const [user] = useState<User | null>(null);
return <p>Hello, {user.name}</p>;
}With strict on, the compiler reports 'user' is possibly 'null' at user.name. The fix is to check first, for example user ? user.name : "guest". Later chapters rely on this behavior, so turn strict on from the first day. Turning it on late in a large project means fixing hundreds of errors at once.
jsx
The jsx option tells the compiler how to treat JSX syntax. The values you are likely to meet are:
| Value | Meaning |
|---|---|
| `react-jsx` | Automatic runtime. The compiler imports the JSX helper functions for you. Use this with React 17 and later. |
| `react-jsxdev` | The same as `react-jsx`, with extra development information. Tools usually select it for you. |
| `react` | Classic runtime. Every file that uses JSX must `import React from "react"`. |
| `preserve` | Leaves JSX untouched for another tool to handle. Next.js sets this value itself. |
With react-jsx, you can write a component without importing React:
export function Hello() {
return <h1>Hello</h1>;
}With the classic react value, that same file fails with 'React' refers to a UMD global, but the current file is a module, or with a runtime error that React is not defined. If you see that message in a modern project, check jsx first.
module and moduleResolution
module sets the module format of the output, and moduleResolution sets how the compiler finds the file behind an import.
"module": "esnext"keeps modernimportandexportsyntax. The bundler then handles it."moduleResolution": "bundler"follows the rules bundlers use. It understandspackage.jsonexportsfields and lets you import./Cardwithout writing the file extension.
The bundler setting needs TypeScript 5.0 or later. On older versions, use "node" instead. If you build for plain Node.js without a bundler, use node16 or nodenext, which require file extensions in relative imports.
noEmit
"noEmit": true tells tsc not to write JavaScript files. The bundler already produces the output, so tsc acts only as a checker. Add a script to run it:
{
"scripts": {
"typecheck": "tsc --noEmit"
}
}Run npm run typecheck in CI, so type errors fail the build even though the bundler ignores them.
Options you will often add
The minimal file works, but real projects usually add a few more options. Add them when you need them, not by default.
| Option | Why add it | Column |
|---|---|---|
| `"target": "ES2020"` | Sets the language level the compiler assumes. Newer syntax like `?.` and `??` is kept as written. | |
| `"lib": ["DOM", "DOM.Iterable", "ES2020"]` | Loads the type definitions for browser APIs such as `HTMLInputElement`. Without `DOM`, those types do not exist. | |
| `"skipLibCheck": true` | Skips checking `.d.ts` files in `node_modules`. It speeds up checks and avoids errors caused by type packages you do not control. | |
| `"isolatedModules": true` | Reports code that a single-file transpiler cannot handle. Vite requires it. | |
| `"esModuleInterop": true` | Lets you use default imports from CommonJS packages. | |
| `"noUncheckedIndexedAccess": true` | Makes `array[0]` have type `T \ | undefined`. It is stricter than `strict` and optional. |
The lib option deserves attention. If you set lib yourself and leave out DOM, then HTMLInputElement and ChangeEvent<HTMLInputElement> fail with Cannot find name 'HTMLInputElement'. If you do not set lib, the default for your target includes DOM.
Type-only imports
With isolatedModules, a transpiler that processes one file at a time cannot always tell whether an imported name is a type or a value. Use import type for names that exist only as types:
import type { ReactNode } from "react";
import { useState, type ChangeEvent } from "react";The type keyword guarantees the import is removed from the output. The examples in this tutorial use this style. The option verbatimModuleSyntax makes it mandatory, which is a good choice for new projects.
Verify the setup
Create src/Check.tsx with a deliberate type error:
interface BadgeProps {
label: string;
}
function Badge({ label }: BadgeProps) {
return <span>{label}</span>;
}
export function Check() {
return <Badge label={42} />;
}Run the checker:
npx tsc --noEmitYou should see an error like Type 'number' is not assignable to type 'string' on the label attribute. If the command prints nothing, the file is not part of the project. Common reasons are:
- There is no
includefield and the file sits outside the folder that holdstsconfig.json. - An
includeorexcludepattern leaves outsrc. - A
tsconfig.jsonin a parent or child folder is being picked up instead.
Add "include": ["src"] at the top level of the config to make the scope explicit. Fix the error afterward by passing label="42".
Common setup errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find module 'react' or its corresponding type declarations` | `@types/react` is missing. | Install `@types/react`. |
| `JSX element implicitly has type 'any' because no interface 'JSX.IntrinsicElements' exists` | `@types/react` is missing or the `jsx` option is not set. | Install the types and set `jsx`. |
| `Cannot use JSX unless the '--jsx' flag is provided` | The `jsx` option is missing. | Set `"jsx": "react-jsx"`. |
| `'React' refers to a UMD global` | `jsx` is `react` but React is not imported. | Use `react-jsx`, or import React. |
| `Cannot find name 'HTMLInputElement'` | `lib` has no `DOM`. | Add `"DOM"` to `lib`. |
| No errors reported for a file that obviously has one | The file is excluded from the project. | Check `include` and `exclude`. |
Summary of the working model
- A TSX file is checked by
tscand transformed by a separate transpiler. strictenables the null and implicitanychecks that later chapters depend on.jsx: "react-jsx"removes the need to import React in every file.noEmitmakestsca pure checker, and CI should run it.@types/reactprovides every React type you will use in the rest of this tutorial.
Exercise
Your Vite app runs without problems, but a teammate points out that <Badge label={42} /> passes a number to a string prop. Why did the dev server not report it, and what should you add so this is caught before merge?
Show answer
Vite transpiles TSX with a tool that strips types and does not check them, so type errors never stop the dev server. Run the type checker, tsc --noEmit, as an npm run typecheck script and add it to CI so type errors fail the build.
Exercise
A file that uses JSX fails with 'React' refers to a UMD global, but the current file is a module, and you do not import React in any component. Which tsconfig.json option do you check, and what value should it have?
Show answer
Check jsx. Set it to "react-jsx" so the compiler uses the automatic runtime and no import React from "react" is needed.
Exercise
With strict turned off, useState<User | null>(null) followed by user.name compiles. Which strict flag makes the compiler reject it, and what is a safe way to write the access?
Show answer
strictNullChecks rejects it, because user may be null. Check before use, for example user ? user.name : "guest" or user?.name.