Category: react
how to use TypeScript in react
Published on 20 Apr 2026
Explanation
Use the Create React App command with
the TypeScript template to start a React
project configured with TypeScript.
Code:
npx create-react-app my-app --template typescript
Explanation
Move into the project directory after
creating
the React TypeScript application.
Code:
cd my-app
Explanation
Run the React TypeScript application
locally to
verify setup.
Code:
npm start
Explanation
React components written with TypeScript
use the
.tsx extension instead of .js or .jsx.
Code:
const App: React.FC = () => {
return <h1>Hello TypeScript React</h1>;
};
export default App;
Explanation
Use TypeScript interfaces to define
component props
for better type safety.
Code:
interface Props {
name: string;
}
const Greeting: React.FC<Props> = ({ name })
=> {
return <h2>Hello {name}</h2>;
};
Explanation
Specify the type of state variables using
generics in React hooks.
Code:
const [count, setCount] = useState<number>(0);
Explanation
TypeScript helps define event types
for safer
event handling in React components.
Code:
const handleClick = (event:
React.MouseEvent<HTMLButtonElement>) => {
console.log("Button clicked");
};
Explanation
Install additional type definitions
when using external
libraries in React TypeScript projects.
Code:
npm install @types/react @types/react-dom