MENU
TypeScript
Developed by Microsoft, and with a syntax somewhat similar to Flow's, TypeScript builds on JavaScript by adding static type definitions. It has become the dominant type-checking solution in the broader JavaScript ecosystem — far more widely used than Flow — and supports Express, Vue, Angular, and React alike.
To create a new project with TypeScript support, use a modern build tool such as Vite:
| npm create vite@latest my-app -- --template react-ts |
(Older tutorials may show 'npx create-react-app my-app --template typescript' — Create React App has since been officially deprecated, so Vite or a framework like Next.js is now the recommended starting point.)
Below is a sample code snippet that uses TypeScript with React:
// src/components/StatefulHello.tsx
import { useState } from "react";
export interface Props {
name: string;
enthusiasmLevel?: number;
}
function Hello({ name, enthusiasmLevel }: Props) {
const [currentEnthusiasm, setCurrentEnthusiasm] = useState(enthusiasmLevel || 1);
const onIncrement = () => setCurrentEnthusiasm(currentEnthusiasm + 1);
const onDecrement = () => setCurrentEnthusiasm(currentEnthusiasm - 1);
if (currentEnthusiasm <= 0) {
throw new Error('You could be a little more enthusiastic. :D');
}
return (
<div className="hello">
<div className="greeting">
Hello {name + getExclamationMarks(currentEnthusiasm)}
</div>
<button onClick={onDecrement}>-</button>
<button onClick={onIncrement}>+</button>
</div>
);
}
export default Hello;
function getExclamationMarks(numChars: number) {
return Array(numChars + 1).join('!');
}For a good cheatsheet on how to use TypeScript with React, refer to the React TypeScript Cheatsheet.