← Back to TypeScript Course | Chapter 14: TypeScript with React | Lesson 1 of 8

Setting Up React TypeScript Project

React works naturally with TypeScript and can provide type safety for components, props, state, events, and hooks. A React TypeScript project normally uses .tsx files for components that contain JSX.

Creating a React TypeScript Project

Creating a React + TypeScript project (via Vite or Create React App's TypeScript template) scaffolds a project where component files use the .tsx extension, which allows JSX syntax alongside TypeScript's type annotations.

Example: Creating a React TypeScript Project

typescript
// npm create vite@latest my-app -- --template react-ts
console.log("Scaffolds a project where components use the .tsx extension");

Writing a TSX Component

Writing a TSX component means the file can mix JSX markup with typed props and typed local variables in the same function, with the .tsx extension telling the compiler to parse JSX tags rather than treating < as a comparison operator.

Example: Writing a TSX Component

typescript
import React from "react";

function Greeting(): React.JSX.Element {
	const name: string = "Ravi";
	return <h1>Hello, {name}</h1>;
}

export default Greeting;

Typing Component Variables

Typing component variables — like state, refs, or computed values inside the component — follows normal TypeScript rules, since a React component is ultimately just a typed function that happens to return JSX.

Example: Typing Component Variables

typescript
import React from "react";

function Counter(): React.JSX.Element {
	const initialCount: number = 0;
	return <p>Count: {initialCount}</p>;
}

export default Counter;

Using TypeScript Configuration

Using TypeScript configuration in a React project typically sets jsx to react-jsx in tsconfig.json, telling the compiler how to transform JSX syntax into the actual function calls React expects at runtime.

Example: Using TypeScript Configuration

typescript
// tsconfig.json
// { "compilerOptions": { "jsx": "react-jsx" } }
console.log("jsx: react-jsx tells the compiler how to transform JSX");

Starting with a Typed App

Starting from a fully typed app template means props, state, and event handlers are checked from the very first component you write, catching mismatches like a misspelled prop name before the app ever runs in a browser.

Example: Starting with a Typed App

typescript
import React from "react";

interface AppProps {
	title: string;
}

function App({ title }: AppProps): React.JSX.Element {
	return <h1>{title}</h1>;
}

export default App;
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.