Sub topic 1
Setting up TypeScript for TSX
Prerequisites
Assume you know function components, props, state, and JSX. You should also know TypeScript interfaces, type aliases, unions, and generics. A bundler such as Vite or Next.js should already run your React project.
Configure TSX checking
TSX is TypeScript syntax that allows JSX. Configure the TypeScript compiler to check it in strict mode:
{
"compilerOptions": {
"strict": true,
"jsx": "react-jsx",
"module": "esnext",
"moduleResolution": "bundler",
"noEmit": true
}
}The jsx option selects the automatic JSX runtime. strict enables checks that catch missing or incompatible values. noEmit tells TypeScript to check files without generating JavaScript. Your bundler still transforms the TSX files.
Type component props
Props are the inputs passed to a component. Describe them with an interface or a type alias. Both work well for object-shaped props.
import type { ReactNode } from "react";
interface CardProps {
title: string;
variant?: "plain" | "outlined";
children: ReactNode;
}
type BadgeProps = {
label: string;
tone: "info" | "warning";
};
export function Card({
title,
variant = "plain",
children,
}: CardProps) {
return (
<section className={`card card-${variant}`}>
<h2>{title}</h2>
{children}
</section>
);
}title is required and must be a string. The variant? marker makes variant optional. Its union type still limits callers to the two listed strings. A default value supplies "plain" when the caller omits it.
ReactNode is the type of anything React can render, including text, elements, fragments, arrays, and null. Use it for flexible children. Make children optional when the component can render without nested content.
Exercise
What type should a required prop use when a component accepts nested JSX content?
Show answer
Use ReactNode, imported with import type { ReactNode } from "react".