If you don't have Node.js installed, download it from Node.js. You can verify if you have Node and npm installed by running:
node -v npm -v Use the following command to create a new React app using TypeScript:
npx create-react-app react-getting-started --template typescript cd react-getting-started This sets up a React project with TypeScript.
Navigate to the project directory and start the development server:
npm start This will open the app in your browser at http://localhost:3000.
The project structure will look similar to a regular React app, with the main difference being the use of .ts and .tsx files instead of .js:
react-getting-started ├── node_modules ├── public │ ├── index.html │ └── ... ├── src │ ├── App.css │ ├── App.tsx │ ├── index.tsx │ └── ... ├── tsconfig.json ├── package.json └── ... -
tsconfig.json: This file contains the configuration for TypeScript. -
src/index.tsx: The main entry point for your app. -
src/App.tsx: Your main React component in TypeScript.
Open src/App.tsx and modify it to include TypeScript types:
import React from 'react'; interface AppProps { message: string; } const App: React.FC<AppProps> = ({ message }) => { return ( <div> <h1>{message}</h1> <p>Welcome to your first React app with TypeScript.</p> </div> ); }; export default App; In this example:
-
AppPropsis an interface that defines the props that the component accepts (messageof typestring). -
React.FCis the type for functional components.
To use this component, modify src/index.tsx:
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; ReactDOM.render( <React.StrictMode> <App message="Hello, React with TypeScript!" /> </React.StrictMode>, document.getElementById('root') ); When using TypeScript with React, you'll often work with interfaces or types to define the structure of your components' props, state, and more. For example:
-
Props: Define the data that components expect.
-
State: Define the internal state of a component.





