JavaScript and React course ยท Module 12: React and TypeScript
Main Project: Typed Cosmic Dashboard
In this lesson5
Mission control receives data from the whole galaxy: planets, stars and asteroids, each with different fields. The operator filters them, adds new discoveries and switches the console theme for the night watch. One wrong type in such a system and the screen shows "undefined" instead of a star's temperature. Time to combine all the knowledge from this module into one project! You'll build a typed cosmic dashboard that uses:
- Interfaces and types - for planet, mission, and crew data
- Typed components - with full props typing
- useState with generics - for state management
- Typed events - in forms and interactions
- Discriminated unions - for different data types
- Context API with TypeScript - for global state
Project Description
The cosmic dashboard consists of several sections:
- Main panel - displays mission statistics
- Cosmic object list - with filtering by type (planets, stars, asteroids)
- Add form - with full event typing
- Theme toggle - dark/light with Context API
My advice: start with the types, not the JSX. Once the data map is ready, the components practically write themselves, because the editor suggests every field.
Type Architecture
The first step is a base interface with the fields every object shares, plus three variants that extend it with extends. Each variant adds a kind discriminator with a literal type, exactly as in the lesson on discriminated unions:
// Base interface
interface SpaceEntity {
id: string;
name: string;
discoveredYear: number;
}
// Discriminated union - different object types
interface PlanetEntity extends SpaceEntity {
kind: "planet";
radius: number;
habitable: boolean;
}
interface StarEntity extends SpaceEntity {
kind: "star";
temperature: number;
spectralClass: "O" | "B" | "A" | "F" | "G" | "K" | "M";
}
interface AsteroidEntity extends SpaceEntity {
kind: "asteroid";
diameter: number;
composition: string;
}The spectralClass field accepts only the seven real stellar spectral classes, from the hottest O to the coolest M. Now we join the variants into a union and describe the dashboard state:
type CosmicObject = PlanetEntity | StarEntity | AsteroidEntity;
// Dashboard state
interface DashboardState {
objects: CosmicObject[];
filter: CosmicObject["kind"] | "all";
searchQuery: string;
}CosmicObject["kind"] extracts every discriminator value from the union, i.e. "planet" | "star" | "asteroid". We add "all" and the filter knows every allowed option. When you add a fourth variant, the filter updates itself - nothing needs changing by hand.
Generic DataTable Component
The table should display any objects, so it's generic. The new element is the keyof T operator, which returns a union of the field names of type T. Thanks to it, a column can point only at a field that really exists. T[keyof T] in turn means the type of the value of any of those fields.
// Generic table component with full typing
interface Column<T> {
key: keyof T;
label: string;
render?: (value: T[keyof T], item: T) => React.ReactNode;
}
interface DataTableProps<T extends { id: string }> {
data: T[];
columns: Column<T>[];
onRowClick?: (item: T) => void;
}The constraint T extends { id: string } guarantees a key for every row. The optional render lets a column draw its value in its own way, for example with a unit. The component itself:
function DataTable<T extends { id: string }>({
data, columns, onRowClick
}: DataTableProps<T>) {
return (
<table>
<thead>
<tr>
{columns.map(col => (
<th key={String(col.key)}>{col.label}</th>
))}
</tr>
</thead>
<tbody>
{data.map(item => (
<tr key={item.id} onClick={() => onRowClick?.(item)}>
{columns.map(col => (
<td key={String(col.key)}>
{col.render
? col.render(item[col.key], item)
: String(item[col.key])}
</td>
))}
</tr>
))}
</tbody>
</table>
);
}String(col.key) is needed because keyof T can in theory include symbols, while a React key expects a string or number. onRowClick?.(item) calls the function only if the parent passed it.
Typed Add Form
The form also uses a discriminated union: each object kind has different fields, and values from text inputs are stored as string, because that's what e.target.value returns. Conversion to numbers happens only when the object is created.
type NewObjectForm =
| { kind: "planet"; name: string; radius: string; habitable: boolean }
| { kind: "star"; name: string; temperature: string; spectralClass: string }
| { kind: "asteroid"; name: string; diameter: string; composition: string };The component takes an onAdd callback and keeps the selected object kind and the name in state. The submit handler uses React.SubmitEvent (in older projects you'll see the now deprecated React.FormEvent here):
function AddObjectForm({ onAdd }: { onAdd: (obj: CosmicObject) => void }) {
const [kind, setKind] = useState<CosmicObject["kind"]>("planet");
const [name, setName] = useState("");
const handleSubmit = (e: React.SubmitEvent<HTMLFormElement>) => {
e.preventDefault();
// Creates the appropriate object based on the selected type
const id = crypto.randomUUID();
const year = new Date().getFullYear();
// ... object creation logic
};
return (
<form onSubmit={handleSubmit}>
<select
value={kind}
onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>
setKind(e.target.value as CosmicObject["kind"])
}
>
<option value="planet">Planet</option>
<option value="star">Star</option>
<option value="asteroid">Asteroid</option>
</select>
<input value={name} onChange={e => setName(e.target.value)} />
<button type="submit">Add</button>
</form>
);
}crypto.randomUUID() is a built-in browser function that generates a unique identifier - it works on HTTPS pages and on localhost. We didn't give the input an event type, because for a function written directly in the attribute TypeScript infers it. You'll write the missing object creation logic as an exercise: a switch on kind and assertNever in the default branch.
Complete Project
Below you'll find the complete cosmic dashboard implementation with full TypeScript typing. Analyze the code, modify it, and experiment with the types! Try adding a fourth object kind, such as a comet, and watch how many places the compiler points out.
Code for this lesson: App.tsx
import React, { createContext, useContext, useReducer, useState, useRef } from 'react';
// ===== DATA TYPES =====
interface SpaceEntity {
id: string;
name: string;
discoveredYear: number;
}
interface PlanetEntity extends SpaceEntity {
kind: "planet";
radius: number;
habitable: boolean;
}
interface StarEntity extends SpaceEntity {
kind: "star";
temperature: number;
spectralClass: "O" | "B" | "A" | "F" | "G" | "K" | "M";
}
interface AsteroidEntity extends SpaceEntity {
kind: "asteroid";
diameter: number;
composition: string;
}
type CosmicObject = PlanetEntity | StarEntity | AsteroidEntity;
// ===== STATE AND ACTIONS =====
interface DashboardState {
objects: CosmicObject[];
filter: CosmicObject["kind"] | "all";
searchQuery: string;
theme: "dark" | "light";
}
type DashboardAction =
| { type: "ADD_OBJECT"; payload: CosmicObject }
| { type: "REMOVE_OBJECT"; payload: string }
| { type: "SET_FILTER"; payload: DashboardState["filter"] }
| { type: "SET_SEARCH"; payload: string }
| { type: "TOGGLE_THEME" };
function dashboardReducer(state: DashboardState, action: DashboardAction): DashboardState {
switch (action.type) {
case "ADD_OBJECT":
return { ...state, objects: [...state.objects, action.payload] };
case "REMOVE_OBJECT":
return { ...state, objects: state.objects.filter(o => o.id !== action.payload) };
case "SET_FILTER":
return { ...state, filter: action.payload };
case "SET_SEARCH":
return { ...state, searchQuery: action.payload };
case "TOGGLE_THEME":
return { ...state, theme: state.theme === "dark" ? "light" : "dark" };
default:
return state;
}
}
// ===== CONTEXT =====
interface DashboardContextType {
state: DashboardState;
dispatch: React.Dispatch<DashboardAction>;
}
const DashboardContext = createContext<DashboardContextType | undefined>(undefined);
function useDashboard(): DashboardContextType {
const ctx = useContext(DashboardContext);
if (!ctx) throw new Error("useDashboard requires DashboardProvider");
return ctx;
}
// ===== GENERIC COMPONENT =====
interface HasId { id: string; }
function DataList<T extends HasId>({
items, renderItem, emptyMsg = "No data"
}: {
items: T[];
renderItem: (item: T) => React.ReactNode;
emptyMsg?: string;
}) {
if (items.length === 0) return <p className="empty">{emptyMsg}</p>;
return (
<div className="data-list">
{items.map(item => <div key={item.id} className="data-item">{renderItem(item)}</div>)}
</div>
);
}
// ===== CARD COMPONENT =====
function ObjectCard({ obj, onRemove }: { obj: CosmicObject; onRemove: (id: string) => void }) {
const icons = { planet: "P", star: "S", asteroid: "A" };
const colors = { planet: "#22c55e", star: "#f59e0b", asteroid: "#ef4444" };
const renderDetails = (): React.ReactNode => {
switch (obj.kind) {
case "planet":
return <><p>Radius: {obj.radius} km</p><p>{obj.habitable ? "Habitable" : "Uninhabitable"}</p></>;
case "star":
return <><p>Temp: {obj.temperature}K</p><p>Class: {obj.spectralClass}</p></>;
case "asteroid":
return <><p>Diameter: {obj.diameter} km</p><p>Composition: {obj.composition}</p></>;
}
};
return (
<div className="object-card" style={{ borderLeftColor: colors[obj.kind] }}>
<div className="card-top">
<span className="obj-icon" style={{ background: colors[obj.kind] }}>{icons[obj.kind]}</span>
<div>
<h3>{obj.name}</h3>
<span className="year">Discovered: {obj.discoveredYear}</span>
</div>
<button className="remove-btn" onClick={() => onRemove(obj.id)}>X</button>
</div>
{renderDetails()}
</div>
);
}
// ===== FORM =====
function AddForm() {
const { dispatch } = useDashboard();
const [kind, setKind] = useState<CosmicObject["kind"]>("planet");
const [name, setName] = useState("");
const nameRef = useRef<HTMLInputElement>(null);
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!name.trim()) return;
const base = { id: Date.now().toString(), name, discoveredYear: 2026 };
let obj: CosmicObject;
switch (kind) {
case "planet":
obj = { ...base, kind: "planet", radius: 6371, habitable: false };
break;
case "star":
obj = { ...base, kind: "star", temperature: 5778, spectralClass: "G" };
break;
case "asteroid":
obj = { ...base, kind: "asteroid", diameter: 100, composition: "rock" };
break;
}
dispatch({ type: "ADD_OBJECT", payload: obj });
setName("");
nameRef.current?.focus();
};
return (
<form onSubmit={handleSubmit} className="add-form">
<select value={kind} onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>
setKind(e.target.value as CosmicObject["kind"])
}>
<option value="planet">Planet</option>
<option value="star">Star</option>
<option value="asteroid">Asteroid</option>
</select>
<input ref={nameRef} value={name} onChange={e => setName(e.target.value)} placeholder="Object name" />
<button type="submit">Add</button>
</form>
);
}
// ===== STATISTICS =====
function Stats() {
const { state } = useDashboard();
const total = state.objects.length;
const planets = state.objects.filter(o => o.kind === "planet").length;
const stars = state.objects.filter(o => o.kind === "star").length;
const asteroids = state.objects.filter(o => o.kind === "asteroid").length;
return (
<div className="stats">
<div className="stat"><span className="stat-num">{total}</span><span>Total</span></div>
<div className="stat"><span className="stat-num" style={{color:"#22c55e"}}>{planets}</span><span>Planets</span></div>
<div className="stat"><span className="stat-num" style={{color:"#f59e0b"}}>{stars}</span><span>Stars</span></div>
<div className="stat"><span className="stat-num" style={{color:"#ef4444"}}>{asteroids}</span><span>Asteroids</span></div>
</div>
);
}
// ===== MAIN APP =====
const initialState: DashboardState = {
objects: [
{ id: "1", kind: "planet", name: "Kepler-442b", discoveredYear: 2015, radius: 8200, habitable: true },
{ id: "2", kind: "star", name: "Betelgeuse", discoveredYear: 1603, temperature: 3500, spectralClass: "M" },
{ id: "3", kind: "asteroid", name: "Apophis", discoveredYear: 2004, diameter: 370, composition: "iron, nickel" },
{ id: "4", kind: "planet", name: "Proxima b", discoveredYear: 2016, radius: 7100, habitable: true },
{ id: "5", kind: "star", name: "Sirius", discoveredYear: -200, temperature: 9940, spectralClass: "A" },
],
filter: "all",
searchQuery: "",
theme: "dark"
};
function Dashboard() {
const { state, dispatch } = useDashboard();
const filtered = state.objects
.filter(o => state.filter === "all" || o.kind === state.filter)
.filter(o => o.name.toLowerCase().includes(state.searchQuery.toLowerCase()));
return (
<>
<header className="header">
<h1>Cosmic Dashboard</h1>
<button onClick={() => dispatch({ type: "TOGGLE_THEME" })}>
{state.theme === "dark" ? "Light" : "Dark"}
</button>
</header>
<Stats />
<AddForm />
<div className="toolbar">
<input
className="search"
value={state.searchQuery}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
dispatch({ type: "SET_SEARCH", payload: e.target.value })
}
placeholder="Search..."
/>
<div className="filter-btns">
{(["all","planet","star","asteroid"] as const).map(f => (
<button key={f}
className={"fbtn " + (state.filter === f ? "active" : "")}
onClick={() => dispatch({ type: "SET_FILTER", payload: f })}
>
{f === "all" ? "All" : f === "planet" ? "Planets" : f === "star" ? "Stars" : "Asteroids"}
</button>
))}
</div>
</div>
<DataList<CosmicObject>
items={filtered}
renderItem={(obj) => (
<ObjectCard obj={obj} onRemove={(id) => dispatch({ type: "REMOVE_OBJECT", payload: id })} />
)}
emptyMsg="No objects found"
/>
</>
);
}
function App() {
const [state, dispatch] = useReducer(dashboardReducer, initialState);
return (
<DashboardContext.Provider value={{ state, dispatch }}>
<div className={"app " + state.theme}>
<Dashboard />
</div>
</DashboardContext.Provider>
);
}
export default App;After this project you're ready for typed applications in the next worlds, where TypeScript will accompany you in Next.js and on the server.
Remember: a well-typed dashboard is a mission control center where every gauge shows exactly what it promises.
Docs entries used in this lesson
Spotted a mistake in this lesson?