Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 7.1Setting up React with TypeScript

TypeScript checks the values passed between React components before the application runs. Files containing both TypeScript and JSX use the .tsx extension; ordinary TypeScript modules use .ts.

Create the project

Terminal
npm create vite@latest typed-task-list -- --template react-ts
cd typed-task-list
npm install
npm run dev
    

What TSX adds

React still behaves in the same way. TypeScript checks component inputs, event values and state updates, then the build removes the types. A type error is development feedback, not a runtime condition shown to the user.

Typing props

TSX
type TaskItemProps = {
  title: string;
  complete?: boolean;
};

function TaskItem({
  title,
  complete = false
}: TaskItemProps) {
  return (
    <li className={complete ? "task task--complete" : "task"}>
      {title}
    </li>
  );
}
    

The type describes the component's public inputs. The question mark makes complete optional, matching its default. TypeScript now rejects a missing title or a non-boolean completion value at the call site.

  1. Create the project using the React TypeScript template.
  2. Add id, title and complete to a Task type.
  3. Give TaskItem a single task prop using that type.
  4. Try passing an incorrect value and read the editor error before correcting it.

Extension challenge: add an optional priority limited to "low", "normal" or "high".

Feedback 👍
Comments are sent via email to me.