HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 3“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
TypeScript for Production Full-Stack Development
TechLearningPro's Monday board double-counted a cohort after a "small" API change.
Course progress0%
Focus
16 guided sections
Practice signal
Concept-first lesson
Career prep
Foundation builder
AI-Powered Full Stack Development · Lesson 03 · Full-Stack Engineering Foundations
Lesson Overview
TechLearningPro's Monday board double-counted a cohort after a "small" API change. The progress handler accepted JSON, the field completed arrived as the string "true", and a truthy check in the Node.js service treated every non-empty string as success. The React player had been written against a boolean. TypeScript was in the repo. "strict": true was not, and the HTTP boundary was typed as any, so the compiler never saw the lie. The same week, a tutor response typed as any let an extra completed: true field ride along in a log mapper and into a draft table that an analyst summed by accident.
This lesson makes TypeScript do production work. You will turn on a strict compiler, model completion and tutor results as discriminated unions, brand tenant and user ids so they cannot be swapped, and parse unknown JSON before any domain function sees it. Types erase at runtime. The parser is the part that protects the Monday board. The compiler is the part that forces you to write the parser and to handle every failure branch.
The contracts continue lesson 1. The repository hygiene continues lesson 2. No provider SDK appears here. The sample parses your own API's JSON.
Learning Objectives
By the end of this lesson you will be able to:
Explain why TypeScript types disappear at runtime and where a parser must stand.
Configure a strict compiler so implicit any, unchecked null, and unused results are visible.
Replace any at the JSON boundary with unknown and a narrowing parser.
Model success and failure as a discriminated union the caller must handle.
Use branded types so a TenantId cannot be passed where a UserId is required.
Share one domain module between the API and the tests that stand in for the web app.
Reject model-shaped data that includes a completion flag the domain does not define.
Write tests that feed malformed JSON, swapped ids, and a valid payload.
Describe the cost of strictness: more upfront errors, fewer production mis-counts.
You can read functions, objects, and arrays in JavaScript. You do not need prior TypeScript on a large codebase.
Install typescript as a dev dependency in the lab package. The examples target TypeScript 5.4 or newer language behavior for unknown, unions, and satisfies. Confirm the version you install with npx tsc --version and read the handbook if a flag name differs.
Detailed Core Concepts
Why the language is on the critical path
The learning platform is one product with two runtimes: the browser and the server. Both speak JSON, which has no tenant brand and no union tag until you invent them. TypeScript is the shared description of those inventions. It does not replace PostgreSQL constraints, authorization, or tests. It removes an entire class of mistakes before CI runs: swapped arguments, forgotten error branches, and fields that exist only in a programmer's memory.
any opts out of that description. A value of type any accepts every property read and every assignment. It is how the string "true" became a completion. unknown is the honest type for bytes you have not inspected. You may hold it. You may not read completed on it until a parser says it is a boolean.
Strict compiler, strict habits
A production tsconfig for this course starts here:
json
{
"compilerOptions":{
"target":"ES2022",
"module":"NodeNext",
"moduleResolution":"NodeNext",
"strict":true,
"noUncheckedIndexedAccess":true,
"exactOptionalPropertyTypes":true,
"noImplicitOverride":true,
"noFallthroughCasesInSwitch":true,
"forceConsistentCasingInFileNames":true,
"verbatimModuleSyntax":true,
"skipLibCheck":true,
"outDir":"dist",
"rootDir":"src"
},
"include":["src"]
}
strict enables strictNullChecks and noImplicitAny, among other flags. noUncheckedIndexedAccess makes array[i] include undefined, which matches runtime reality. exactOptionalPropertyTypes stops you from assigning undefined to an optional property that means "absent." verbatimModuleSyntax keeps import type honest so type-only imports do not remain in the emitted JavaScript. If a flag is unfamiliar, leave it on and fix the errors; turning it off recreates the Monday bug class.
Discriminated unions
A discriminated union is a set of object types that share a literal field. The tutor result from lesson 1 is one. Completion parsing is another:
typescript
typeParseResult<T>=
|{ ok:true; value:T}
|{ ok:false; error:string};
After if (result.ok), TypeScript narrows result to the success branch. The failure branch has error and does not have value. That is how you force every caller to handle malformed JSON. Exceptions still exist for programmer errors. Expected failures—bad input, failed quiz, missing draft—belong in the union so they show up in the type and in logs as data, not as stack traces.
Branded ids
Structural typing means { tenantId: string; userId: string } accepts any strings. A query written with the arguments reversed still typechecks and then reads another tenant's rows or none. Branding attaches a phantom tag:
The tag does not exist at runtime. The parser is the only function allowed to cast a checked string into a brand. Everywhere else, the compiler refuses to pass a UserId to a parameter that wants a TenantId.
Shared modules
Put types and parsers in packages/domain. The API imports them. Tests import them. The React app, when you build it, imports the types and the same parser for any JSON it receives. Duplicating an interface in the client "because the server already checks" is how "true" comes back. One module, one definition of CompletionFact.
What the model is allowed to look like
A tutor payload in this lesson is { text: string; promptVersion: string }. If the JSON also contains completed, the parser strips it by constructing a new object with only the known fields. Passing the raw object through would let extra fields survive into a mapper. This is the type-level version of lesson 1's rule: draft text is not a fact.
Deterministic checks around probabilistic text
The parser is deterministic. Given the same bytes, it returns the same ParseResult. The string inside text may have been produced by a model and may be wrong. Typing it as string does not make it true. It makes the surrounding system unable to confuse it with a boolean completion flag.
Architecture and Request Flow
flowchart TB
subgraph edge [HTTP edge]
Body[JSON body as unknown]
Parser[parseCompletionBody]
end
subgraph domain [packages/domain]
Ids[Branded TenantId and UserId]
Fact[CompletionFact]
Draft[TutorDraft]
end
subgraph runtimes [Runtimes]
API[Node.js API]
UI[React player]
end
Body --> Parser
Parser -->|ok| Ids
Ids --> Fact
Parser -->|error| API
Fact --> API
Draft --> UI
API --> UI
Malformed JSON stops at the parser. A valid body becomes branded ids and a fact whose source is a literal union. The UI renders TutorDraft.text and does not receive a completion writer.
Step-by-step Implementation
Create packages/domain. The files compile with the tsconfig above and run under Node.js test runner via node --experimental-strip-types.
The unique symbol brand is erased. The pattern is the runtime check: ids are short, lowercase, and predictable so logs stay safe and weird payloads fail closed.
A client that sends "completed": "true" gets completed_not_boolean. The Monday board never sees a fact. Notice the returned object is built field by field. Extra JSON keys are dropped.
If a model gateway returns { text, promptVersion, lessonId, completed: true }, parseTutorDraft yields a TutorDraft with three fields. The completion flag does not typecheck on TutorDraft and does not exist on the value you pass onward.
Callers that parsed ids can call progressKey. Callers that still have plain strings cannot, unless they bypass the parser with a cast. Code review treats as TenantId outside ids.ts as a defect.
Step 5: Compile
bash
npx tsc --noEmit -p packages/domain
Fix every error. Silencing with any or @ts-ignore is a failed lab. // @ts-expect-error is acceptable only on a line you are proving does not compile, with a comment that says what must stay rejected.
Security
Input validation is parseCompletionBody and parseTutorDraft. The type system does not run on the wire. The parsers do.
Authorization is not a type. A well-typed TenantId can still be the wrong tenant if the session was ignored. The API must compare the parsed tenant to the session tenant and reject mismatches before a query.
Least privilege in the code: only ids.ts brands strings. Domain functions accept brands, not raw strings.
Injection via ids is constrained by ID_PATTERN. That is not a SQL parameterization strategy. When these ids reach PostgreSQL, queries still use parameters. The pattern reduces log forging and accidental query concatenation in the meantime.
Secrets do not belong in types or in string literal examples. This package has no key fields.
Tenant isolation depends on the brand plus the session check. Dropping the brand "to make the ORM happy" and passing string reopens argument swaps.
exactOptionalPropertyTypes and fresh object construction also limit mass assignment: unknown JSON properties are not copied onto CompletionFact.
Error Handling
ParseResult errors are stable codes: body_not_object, bad_id, completed_not_boolean, not_complete, bad_source, bad_timestamp, empty_text, text_too_long. The HTTP layer maps them to 400 with the code in a JSON body. It does not interpolate the raw payload into the message; the payload may contain someone else's data pasted into the wrong field.
Programmer errors—calling progressKey with a cast to silence the compiler—are defects, not client errors. Do not catch them and turn them into bad_id. Let tests fail.
Exhaustive switches keep new union members honest:
test("drops a completion flag smuggled on a tutor draft",()=>{
const parsed =parseTutorDraft({
lessonId:"lesson_01",
promptVersion:"tutor-explain-v1",
text:"Read the excerpt again.",
completed:true,
});
assert.equal(parsed.ok,true);
if(parsed.ok){
assert.equal("completed"in parsed.value,false);
assert.equal(parsed.value.text,"Read the excerpt again.");
}
});
Run with node --experimental-strip-types --test src/completion.test.ts. Add a case for source: "model" and expect bad_source. That test is the architecture rule from lesson 1 encoded as a regression.
Performance and Cost
Parsing a small JSON body is cheap next to a database round trip or a model call. Do it anyway, on every request, including internal job payloads. The expensive failure is a wrong fact replicated into the Monday board and into backups.
Strict compilation adds CI minutes, not production latency. skipLibCheck keeps dependency declaration files from dominating that time; it does not skip your code. Avoid elaborate type-level computation for runtime validation. The parsers above are ordinary functions and stay readable in an incident.
Sharing packages/domain between browser and server can pull Node-only code into the client bundle if you are careless. Keep this package free of fs, network, and secrets. The React bundle should contain types and parsers, not the database client. Measure the client bundle when you add the package to the player; a domain module that imports a server logger is a performance and a security defect.
Token cost is unaffected by types. The parser's text_too_long cap is a backstop so a draft cannot store an unbounded string. The real token cap remains on the model port from lesson 1.
Knowledge Check
1. What problem does production TypeScript solve here?
It stops the progress API and the tutor draft from accepting shapes the Monday board will misread, and it makes swapped tenant and user ids a compile error. It does this only when strict is on, any is absent at the boundary, and a parser checks runtime JSON.
2. What alternatives exist, and when would you choose each?
A shared packages/domain parser fits this platform because the browser and the server both see the same JSON. Duplicated interfaces fit a spike that will be deleted, and they drift. Schema libraries can replace the hand-written parsers when the team wants a single declaration that emits both types and runtime checks; the boundary rule stays the same: unknown in, domain type out. Plain JavaScript with conventions fits scripts, not the completion path.
3. Which data, identity, and trust boundaries matter?
JSON from the client is unknown. Branded ids are trusted only after parseTenantId and a session match. TutorDraft is trusted as a shape, not as truth. CompletionFact.source cannot be a model. Casts outside ids.ts cross the boundary illegally.
4. What can fail, and how should the system respond?
Bad JSON returns a ParseResult error code and HTTP 400. A failed quiz never becomes a fact. Extra fields on a draft are dropped. A new union member fails compilation in exhaustive switches until a label and a test exist. Authorization mismatches are rejected even when the body parsed.
5. How would you test quality, security, performance, and cost?
Tests cover a valid fact, the string "true", a smuggled completed on a draft, and source: "model". Security review searches for any and for as TenantId outside the id module. Performance review keeps the package free of server-only imports. Cost review confirms the text length cap and that CI runs tsc --noEmit on every pull request.
Hands-on Assignment
Lab note. No API keys, no network calls. The inputs are local objects and JSON strings.
Problem. Implement the domain package so the string "true" cannot complete a lesson and a tutor payload cannot carry a completion flag into stored state.
Tasks.
Add the strict tsconfig and the modules in this lesson.
Make npx tsc --noEmit pass with zero errors and zero any.
Run the three tests and add the source: "model" case.
Write a snippet in a comment or a discarded file that swaps tenantId and userId into progressKey, and show the compiler error. Do not "fix" it with a cast.
List the error codes and the HTTP status you will use for each.
State where the session tenant is compared to CompletionFact.tenantId. The parser does not do that comparison; name the API function that will.
Deliverable. Compiling source, test output, the compiler error for swapped ids, and the error-code table.
Challenge. Add noUncheckedIndexedAccess usage: a function that reads the first lesson id from string[] and returns ParseResult with error: "missing" when the array is empty. Show that the compiler forces the check.
Rubric. Conceptual accuracy 20%. Strict compile and parsers 25%. Boundary security 20%. Tests including the string-boolean case 20%. Error-code and session notes 15%.
Common Mistakes
Typing the request body as any. Symptom: "true" completes a lesson. Cause: strictness bypassed at the edge. Fix: accept unknown and parse.
Trusting the compiler without a parser. Symptom: unit tests pass with object literals while production JSON still lies. Cause: types erased. Fix: tests must pass raw objects that mimic JSON, including wrong types.
Casting to a brand at the call site. Symptom: swapped ids compile again. Cause: as TenantId used as a shortcut. Fix: brands are minted only in ids.ts.
Copying the JSON object into the domain with a spread. Symptom: completed reappears on a draft and an analyst sums it. Cause: excess property copy. Fix: construct the domain object field by field.
Turning off strict to finish a migration. Symptom: the Monday bug class returns. Cause: flags treated as style. Fix: strict on day one for new packages; migrate old files in slices.
Sharing a package that imports the database client. Symptom: the browser bundle contains server code and secrets-shaped config. Cause: one index file exported everything. Fix: domain package stays pure; server code lives in the API.
Using optional fields for errors. Symptom: callers forget to check error and read value undefined. Cause: no discriminant. Fix: { ok: true } | { ok: false } and narrow.
Summary
Production TypeScript on this platform is a strict compiler plus parsers that turn unknown JSON into branded ids, a completion fact with a closed source, and a tutor draft that cannot carry a completion flag. The type system forces callers to handle ParseResult. It does not see the wire, and it does not check the session. Those remain runtime duties, tested with the same malformed payloads that broke the Monday board.
Next Lesson Preview
Modern JavaScript, Async Programming and Web APIs takes these pure parsers and calls them from asynchronous HTTP, with timeouts and cancellation, on the Node.js runtime. The /learn/typescript track goes deeper on generics and tooling when you want more language surface than this lesson's production slice.