Full-stack: sharing types between client and server
The page and the server each passed their checks and the page still broke. Give both sides one Task type in a shared file, see a rename fail the check on both sides, check at the page's edge what an old server really sends, and meet the tools larger projects use for the same job.
TypeScript
Types
Full-stack: sharing types between client and server. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Picture the next step. Your server from the last lesson answers
GET /tasks with the list, so you change TaskKit's React page to ask
it for its tasks,1 and open the page. It is blank. The browser's
console, the panel where it shows a page's errors, says Objects are not valid as a React child (found: object with keys {title, done}).
The page was written for a list of strings, the server sends a list
of objects, and both sides had passed their checks.
Nothing was wrong with either check. Each one read its own side,
and the mistake sat between them, where no check looks. In this
lesson you give the page and the server one Task type, so a change
on one side is found on the other before anything runs. By the end
you also question, at the page's edge, what the server really
sends, and you know the tools larger projects use for the same job.
Two programs, two checks
Writing both sides of an app, the page in the browser and the server
behind it, is called full-stack work. In TaskKit you now own
both: the React page of A1.2 and the server of A1.3. They are two
programs. The page runs in the browser, the server in Node.js, Deno
or Bun, and each is checked on its own, with its own
tsconfig.json.
Between them travels only text. The server turns its tasks into
JSON (JavaScript Object Notation, data written as text) with
Response.json, and the page turns the JSON back into
values, as JSON.parse did in Level 1's Module 12. Types never make
that trip: they vanish when the code runs, as Level 1's 8.2 showed.
So when each side writes its own idea of a task, nothing compares
the two.
One Task type for both sides
The fix is to write the type once, in a file that belongs to neither
side, and have both sides import it. TaskKit's Task moves into
shared/task.ts:
The server's handle.ts and the page's TaskItem.tsx each bring it
in with import type, as Level 1's 9.1 taught. Their files sit in
folders beside shared, so the path starts with .., the folder
that holds this one:
Now each side's check reads the same type. Change it, and both
checks test their own lines against the change. Pick a project with
the switch, then press Next step to walk it, or let it play:
This lesson's blocks run one file at a time, so the block below holds
all three files in one, each part under a comment that names its
file. The check treats it as it treats the three files: one type,
read by both sides. TaskItem's <li> becomes a plain string here,
since this block is .ts, not .tsx, and the last lines call each
side once. Press Run:
The server has the route from the last lesson's first exercise,
GET /tasks/done, and the page marks a task that is done with ✓.
Now press Edit, change done to completed on line 4, and press
Run again. The check refuses the file and names the lines that
still say done: the server's list and its /tasks/done route, and
the page's label. With two separate types, only the server's lines
would have been named; once you fixed them, both checks would pass,
as the first scenario of the timeline shows.
In your own project
On your own computer the three parts are three files, in three
folders of ~/projects/taskkit:
taskkit/
shared/
task.tsthe one Task type
server/
handle.tsthe handler of A1.3
tsconfig.json
The handler uses only Request, Response and URL, which Node,
Deno and Bun all have, so Node's settings can check it whichever
runs it. Five steps set the folders up:
Move handle.ts from ~/projects/taskkit-server (A1.3) into
server, with the /tasks/done route from A1.3's first
exercise.
In taskkit-server/server.ts, change the import to
"../taskkit/server/handle.ts", so Deno or Bun still runs it.
Copy TaskKit's tsconfig.json into server.
Add "include": ["*.ts"] to TaskKit's own tsconfig.json, in
taskkit: include lists the files a check reads, so it keeps
checking index.ts and the files beside it and leaves the new
folders to their own.
Move A1.1's main.ts into web: it is page code, and TaskKit's
own check, which describes Node, refuses its document.
The page's React part starts in web with one component,
TaskItem, which draws a task as an <li> from one task prop
instead of a string. Its check needs React's types, the @types
package of Level 1's 9.3. From the taskkit folder:
Your numbers of packages and the time may differ.
Here are the two files the checks below read, each with the import
on line 1:
shared has no tsconfig.json of its own. Each side's check
follows the import line into shared/task.ts and reads it, as
Level 1's 9.1 said TypeScript follows every import. The two sides
keep two settings files because they run in two places, and A1.1's
rule holds: lib describes the place the code runs. The server's is
TaskKit's file from A1.1; the page's adds the browser and React's
JSX (JavaScript XML, the tags written inside the code):
Two settings are new here. "module": "esnext" with
"moduleResolution": "bundler" finds files the way a bundler
does, the tool that packs a page's files for the browser: the page
is never run by Node, so its imports are read the bundler's way.
Bundlers and dev servers (Vite) starts a React project with a
settings file much like this one. And the page's file has no types line: the
list starts out empty, as Level 1's 9.3 said, so Node's description stays out
of the page's check. React's descriptions still load: with "jsx": "react-jsx", every tag is turned into an import from React, and an import
brings its package's descriptions in, as in 9.3.
Run each side's check from the taskkit folder with -p, short for
project: the folder whose tsconfig.json to use. With done
renamed to completed in shared/task.ts, they print this:
Each error line is one long line in your terminal, broken here to
fit. The server's check names three lines, the page's one: every line
that still says done. Change the four to completed, and both
checks pass. From here on, TaskKit's Task says completed.
The type stays home
A shared type makes the code on both sides agree. It cannot make the
two running programs agree, because the type is gone once they run.
After the rename, the server you started earlier may still be
running in its terminal, with the old code: Node, Deno and Bun read
a file when they start, not when it changes. On a real site, the
page and the server are often put online one after the other, and
a page opened yesterday keeps talking to today's server. Either
way, the page can receive tasks in the old shape.
And the page's check cannot see the old shape. With dom in
lib, the browser's response.json() gives Promise<any>, the
same any TaskKit met in Level 1's 12.4. (Node's types give
unknown instead, as A1.3 said.) Writing Task[] on an any is
the promise nobody checks from Level 1's 12.5, and now an old
server is on the other end. JSON.parse gives any too, so it
stands in for the answer below.
Bad — the shared type written on an
any: a task that is done is drawn as not done, with no error.
So the questions that matter here are asked while the code runs,
like the ones Level 1's 12.5 asked of the forecast. They belong in
shared/task.ts, beside the type: when someone renames a field,
TypeScript refuses parseTask's return line too, and that leads
you to the questions above it. Pick a server with the switch, then
press Next step to walk its answer through the questions, or
let it play:
response.json(): reachedInto data: unknown
Array.isArray(data): passes✓A list?
parseTask(item): passes✓title and completed?
Task[]: reachedDrawn on the page
Only an answer in today's shape becomes a Task[]; an old
server's answer is stopped with the task it sent
All 6 steps shown.Step 1 of 6: response.json()Step 2 of 6: Array.isArray(data)Step 3 of 6: Array.isArray(data): passesStep 4 of 6: parseTask(item)Step 5 of 6: parseTask(item): passesStep 6 of 6: Task[]
All 6 steps shown.
response.json(): reachedInto data: unknown
Array.isArray(data): passes✓A list?
parseTask(item): stops here✕title and completed?
Task[]: never reachedDrawn on the page
parseTask(item) stops hereError: Not a task: {"title":"Buy milk","done":false}
Only an answer in today's shape becomes a Task[]; an old
server's answer is stopped with the task it sent
All 5 steps shown.Step 1 of 5: response.json()Step 2 of 5: Array.isArray(data)Step 3 of 5: Array.isArray(data): passesStep 4 of 5: parseTask(item)Step 5 of 5: parseTask(item): stops here. Error: Not a task: {"title":"Buy milk","done":false}
All 5 steps shown.
Good — the answer goes through
the shared parseTasks, which stops the old shape and names it.
parseTask asks the questions of Level 1's 12.5, one per property,
and builds a new Task from what passed. parseTasks asks for a
list, then hands every item to parseTask with map. In your
project both are exported from shared/task.ts, and the page reads
the server's answer with one line, parseTasks(await response.json()). parseTasks takes data: unknown, so the any
becomes an unknown as it goes in, A1.3's box again. The bad version
drew the wrong page and said nothing; the good one stops at the
first old task and says what arrived, which is the clue that the
server needs a restart.
The page from the start of the lesson cannot happen any more,
either. If the page still kept useState<string[]>, handing its
setTasks the Task[] from parseTasks would be refused before
anything runs (SetStateAction is React's name for what
setTasks takes):
Argument of type 'Task[]' is not assignable to parameter of type 'SetStateAction<string[]>'. The page's state becomes
useState<Task[]>([]), and each item is drawn with TaskItem,
its key now key={task.title}, since a Task is not a string.
Bigger projects, the same idea
A shared folder is the simplest way to keep one type for both
sides. As a project grows, you will meet tools that do the same job
in other ways. None of them is taught here; each has its own
lesson:
Way
It fits when
A shared folder
Both sides live in one repository
A workspace package
Each side is a package of its own
A schema library, such as zod
Type and questions must never differ
tRPC
The page calls the server's functions directly
Types generated from OpenAPI
The server is written in another language
A workspace is npm's way of keeping several packages in one
repository, each with its own package.json, so the page can
import @taskkit/shared by name instead of by a ../ path; Level
3's Project references and monorepos goes into it. A
schema library lets you write a schema, a description of a
value's shape written as code, once: it questions values while the code runs
and gives you the type from it, so they cannot drift: Level 2's zod:
schemas that become types, compared with your hand-written validators
teaches one. tRPC (TypeScript Remote Procedure Call: a call to a function
that runs on another computer) lets the page call the server's functions as if
they were its own, typed from the server's code: Level 3's Inside tRPC:
sharing types between server and client without code generation reads how.
And when the server is not written in TypeScript, the shared thing is a
description of its API (application programming interface, the requests it
answers) in the OpenAPI format, from which a tool writes the types: Bonus
B's openapi-typescript and openapi-fetch: API types generated from an
API description shows it.
Predict before you run
Predict
A newer server adds a due date. What does the page print?
The common mistake: a type kept on the server
Before there is a shared folder, the type already lives somewhere:
in the server's handle.ts, next to the list it describes. Importing
it from there into the page seems the quickest way to share it.
Common mistake
The page imports its type from the server's file
The server keeps Task in handle.ts, beside a save that writes
the list to a file with Node's writeFile, as Level 1's 12.2 did:
The page takes the type from there:
The server's check passes. The page's check follows the import into
handle.ts, reads every line of it, and reaches Node's module,
which the page's settings do not load:
Cannot find name 'node:fs/promises'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.
The fix
Move the type into shared/task.ts, which imports nothing from
either side, and import it from there on both sides:
The page's check now reads shared/task.ts and nothing of the
server's, and passes.
Level 1's 2.8 and 9.3 met this error code for process, and there
the advice it prints was right: TaskKit runs on Node. Here it is
wrong. Add "types": ["node"] to the page's file and the error goes
away, but the page's check now believes Node is there, and accepts
Node's names, such as process, in code that runs in a browser that
has none of them. When the page's check asks for Node, look at which file it
read: a shared file imports from neither side.
Pass all three tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
The first two run on this page, with the files in one block as
above. Press Run to try the code, and Check when you think it
works.
Recap
Recap · 3 questions
Check yourself
Why did both checks pass while the page broke?
Check yourself
Where does a type both sides use belong?
Check yourself
Why share parseTasks, not only the type?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Full-stack: sharing types between client and server
What things are
Word
What it means
Full-stack
Writing both the page and its server
Shared file
A file both sides import; it imports neither
Bigger projects
Workspace, zod, tRPC, OpenAPI: the same idea
Code and commands
Write
To
export interface Task {…}
Write the type once, in shared/task.ts
from "../shared/task.ts"
Import it from a folder beside yours
parseTask(value)
Check one task; throw if it is not one
parseTasks(data)
Check the server's answer on the page
npx tsc -p server
Check the server with its tsconfig.json
npx tsc -p web
Check the page with its tsconfig.json
No types line
Node's description stays out of the page
How it runs
Rule
What it means
One type, two checks
A change fails on every side that uses it
Types stay home
Only text crosses; question what arrives
Questions beside the type
A rename fails their line too
Extra fields pass
A server may add; it may not rename
TS2591 on the page
It read a server file; import from shared
Where to go next
You can now keep the page and the server on one Task: written once
in a shared file, imported by both, checked by both, with parseTasks
beside it, which stops an answer in the wrong shape. That is the core
of full-stack TypeScript, and every tool in the table above builds
on it.
Next is Mobile and desktop apps, where the same TypeScript, and
often the same React, leaves the browser for a phone or a window on
your desktop.
Before you move on, press Edit on the first block of this lesson
and make the page draw from the server's answer instead of its list.
Copy parseTask and parseTasks from the good block into it, change
completed back to done in them, and loop over
parseTasks(await handle(new Request("http://localhost:8000/tasks")).json()).
Predict what it prints, then run it.
Footnotes
A browser lets a page read a server's answer only when the
server allows the page's address, with an
Access-Control-Allow-Origin header. Suppose yours does: this
lesson is about what comes after. ↩
You
Servercheck
Pagecheck
Thepage
You: done → completeddone→completeddone→completed
Server check: checked ✓checked✓checked✓
Page check: checked ✓checked✓checked✓
The page: all not doneallnotdoneallnotdone
Time
You rename the field in the server's own Task, in
server/handle.ts. The page has a Task of its own.
The server's check reads the server's type, and every line of
the server agrees with it.
The page's check reads the page's own Task, which still
says done, so it finds nothing wrong either.
The server sends completed, the page reads done, finds
nothing there, and draws every task as not done. No error.
With one shared Task, both checks find the old name before
anything runs
All 4 steps shown.Step 1 of 4: You: done → completedStep 2 of 4: Server check: checked ✓Step 3 of 4: Page check: checked ✓Step 4 of 4: The page: all not done
All 4 steps shown.
You
Servercheck
Pagecheck
Thepage
You: done → completeddone→completeddone→completed
Server check: 3 errors handle.ts3errorshandle.ts3errorshandle.ts
You rename the field in shared/task.ts, the one Task both
sides import.
The server's check reads the shared type and names the
server's three lines that still say done.
The page's check reads the same type and names the page's
line that still says done.
Nothing with the old name runs. You fix the four lines the
checks named, and both checks pass.
With one shared Task, both checks find the old name before
anything runs
All 4 steps shown.Step 1 of 4: You: done → completedStep 2 of 4: Server check: 3 errors handle.tsStep 3 of 4: Page check: TS2339 TaskItem.tsxStep 4 of 4: The page: never starts
All 4 steps shown.
web/
TaskItem.tsxdraws one task as an <li>
main.tsthe page code of A1.1
tsconfig.json
index.tsTaskKit from Level 1, with its other files
package.json
tsconfig.json
Exercise · Read the code
Read what a passing check says
You renamed a field in shared/task.ts, and npx tsc -p server
passes. What does that tell you about the page?
added 2 packages, and audited 7 packages in 404msfound 0 vulnerabilities
Outputtext
server/handle.ts:4:24 - error TS2353: Object literal may onlyspecify known properties, and 'done' does not exist in type 'Task'.4 { title: "Buy milk", done: false }, ~~~~server/handle.ts:5:24 - error TS2353: Object literal may onlyspecify known properties, and 'done' does not exist in type 'Task'.5 { title: "Call Mom", done: true }, ~~~~server/handle.ts:14:54 - error TS2339: Property 'done' does notexist on type 'Task'.14 return Response.json(tasks.filter((task) => task.done)); ~~~~Found 3 errors in the same file, starting at: server/handle.ts:4
Outputtext
web/TaskItem.tsx:9:12 - error TS2339: Property 'done' does not existon type 'Task'.9 if (task.done) { ~~~~Found 1 error in web/TaskItem.tsx:9
Outputtext
server/handle.ts:1:27 - error TS2591: Cannot find name'node:fs/promises'. Do you need to install type definitions fornode? Try `npm i --save-dev @types/node` and then add 'node' to thetypes field in your tsconfig.1 import { writeFile } from "node:fs/promises"; ~~~~~~~~~~~~~~~~~~Found 1 error in server/handle.ts:1
ts
import type { Task } from "../shared/task.ts";
taskkit.tsts
// shared/task.tsinterface Task { title: string; done: boolean;}// server/handle.tsconst tasks: Task[] = [ { title: "Buy milk", done: false }, { title: "Call Mom", done: true },];function handle(request: Request): Response { const url = new URL(request.url); if (request.method === "GET" && url.pathname === "/tasks") { return Response.json(tasks); } if (request.method === "GET" && url.pathname === "/tasks/done") { return Response.json(tasks.filter((task) => task.done)); } return new Response("Not found", { status: 404 });}// web/TaskItem.tsx, the <li> as a stringfunction label(task: Task): string { let mark = "·"; if (task.done) { mark = "✓"; } return `${mark} ${task.title}`;}// Each side once: the server's done route, then the page's labelconst doneAnswer = handle(new Request("http://localhost:8000/tasks/done"));console.log(await doneAnswer.text());for (const task of tasks) { console.log(label(task));}
ts
interface Task { title: string; completed: boolean;}// What the old server, still running, sendsconst answer = '[{"title":"Buy milk","done":false},' + '{"title":"Call Mom","done":true}]';const tasks: Task[] = JSON.parse(answer);for (const task of tasks) { let mark = "·"; if (task.completed) { mark = "✓"; } console.log(`${mark} ${task.title}`);}
ts
interface Task { title: string; completed: boolean;}function parseTask(value: unknown): Task { if ( typeof value !== "object" || value === null || !("title" in value) || typeof value.title !== "string" || !("completed" in value) || typeof value.completed !== "boolean" ) { throw new Error(`Not a task: ${JSON.stringify(value)}`); } return { title: value.title, completed: value.completed };}function parseTasks(data: unknown): Task[] { if (!Array.isArray(data)) { throw new Error("Not a list of tasks"); } return data.map(parseTask);}// What the old server, still running, sendsconst answer = '[{"title":"Buy milk","done":false},' + '{"title":"Call Mom","done":true}]';try { for (const task of parseTasks(JSON.parse(answer))) { let mark = "·"; if (task.completed) { mark = "✓"; } console.log(`${mark} ${task.title}`); }} catch (error) { if (error instanceof Error) { console.log(`Error: ${error.message}`); }}
ts
interface Task { title: string; completed: boolean;}function parseTask(value: unknown): Task { if ( typeof value !== "object" || value === null || !("title" in value) || typeof value.title !== "string" || !("completed" in value) || typeof value.completed !== "boolean" ) { throw new Error(`Not a task: ${JSON.stringify(value)}`); } return { title: value.title, completed: value.completed };}// What a newer server sendsconst answer = '{"title":"Buy milk","completed":false,"due":"Friday"}';try { const task = parseTask(JSON.parse(answer)); let mark = "·"; if (task.completed) { mark = "✓"; } console.log(`${mark} ${task.title}`);} catch (error) { if (error instanceof Error) { console.log(error.message); }}
Someone renamed title to name in the shared Task, and the
check now refuses the file. Fix the server's part and the page's
part, so it prints the two tasks again.
Loading the editor…
Exercise · Write the code
Give the shared Task an id
A1.2 said a real task has an id, which names it. Make it a number:
add id: number to the shared Task, give the server's two tasks the
ids 1 and 2, and make parseTask ask for an id that is a
number and keep it in the Task it builds.
Loading the editor…
bash
npm install --save-dev @types/react
bash
npx tsc -p server
bash
npx tsc -p web
bash
npx tsc -p web
import type { Task } from "../shared/task.ts";const tasks: Task[] = [ { title: "Buy milk", done: false }, { title: "Call Mom", done: true },];export function handle(request: Request): Response { const url = new URL(request.url); if (request.method === "GET" && url.pathname === "/tasks") { return Response.json(tasks); } if (request.method === "GET" && url.pathname === "/tasks/done") { return Response.json(tasks.filter((task) => task.done)); } return new Response("Not found", { status: 404 });}
import type { Task } from "../shared/task.ts";interface TaskItemProps { task: Task;}export function TaskItem({ task }: TaskItemProps) { let mark = "·"; if (task.done) { mark = "✓"; } return ( <li> {mark} {task.title} </li> );}