Intro to TypeScript & Strong Typing Concepts
Published by Brayan K
Master TypeScript's type system to catch bugs at compile-time, enable better tooling, and write more maintainable code. Learn types, interfaces, generics, and utility types.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Check a program before executing it
TypeScript adds a static checker to JavaScript. It reasons from declarations and control flow; it does not inspect the future contents of a server response. A type can prevent an invalid call in checked code while an untrusted runtime value still needs validation. The useful habit is to keep those two boundaries visible.
Save each TypeScript panel as its own lesson-example.ts in a separate practice folder. Use the TypeScript Playground with strict checking enabled, or create a local project with TypeScript installed and run npx tsc --strict --noEmitOnError --target ES2022 --module ESNext lesson-example.ts. In a larger project, use its tsconfig and normal type-check command. These displayed checks use TypeScript 5.8.3, standard libraries and an empty ambient types list. They do not depend on Node declarations. Compiler wording can differ in another version.
The recorded configuration has strict and noEmitOnError enabled. Strict includes strictNullChecks; it does not include every extra checking option. Our examples do not claim that noUncheckedIndexedAccess or exactOptionalPropertyTypes is enabled. A bundler that only strips types is not a replacement for this checking step. Module Bundlers: Webpack, Parcel, Vite (Overview) owns build output and deployment paths.
A union prevents a misspelled mode before execution
type Mode = "draft" | "published";
function label(mode: Mode): string {
// A literal union describes the two accepted calls in checked code.
return mode === "draft" ? "Edit" : "Read";
}
const mode: Mode = "draft";
console.log(label(mode));Output
Type check passed
EditChecked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
"use strict";
function label(mode) {
// A literal union describes the two accepted calls in checked code.
return mode === "draft" ? "Edit" : "Read";
}
const mode = "draft";
console.log(label(mode));
// ✅ Expected output:
// EditAn invalid call has a compiler diagnostic and no emitted program
type Mode = "draft" | "published";
function label(mode: Mode): string { return mode; }
console.log(label("publshed"));Output
TS2345: Argument of type '"publshed"' is not assignable to parameter of type 'Mode'.Checked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
The second example is intentionally rejected. No JavaScript is emitted under this configuration, so it has no runtime output. Without noEmitOnError, the compiler can emit JavaScript despite diagnostics; do not describe all TypeScript builds as automatically refusing to run. A transpiler can also erase syntax without checking it.
Inference is a useful default; any removes an important check
An inferred number is not a number-or-string slot
let attempts = 2;
attempts = "three";Output
TS2322: Type 'string' is not assignable to type 'number'.Checked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
A let variable can change value while keeping its inferred type. Add a union when both kinds are intentional; do not widen everything to any just to silence the checker. Interfaces and type aliases name shapes for the checker. Neither creates a runtime object, validates a request nor hides a field.
unknown requires a check before using a value
const incoming: unknown = "Draft";
console.log(incoming.toUpperCase());Output
TS18046: 'incoming' is of type 'unknown'.Checked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
Narrow with checks that also run in JavaScript
function printable(value: unknown): string {
if (typeof value === "string") return value.trim();
if (typeof value === "number" && Number.isFinite(value)) return String(value);
return "unusable";
}
console.log(printable(" Draft "));
console.log(printable(12));
console.log(printable(null));Output
Type check passed
Draft
12
unusableChecked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
A type assertion changes the checker’s view, not the value
const unchecked: any = "12";
const asserted = unchecked as number;
console.log(typeof asserted);
console.log(asserted + 1);Output
Type check passed
string
121Checked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
The assertion example compiles because any permits the assignment. It still contains a string at runtime. Use conversion and validation when you mean to transform a value. Prefer unknown for JSON and other external inputs so the next operation must justify the value’s shape. A user-written type predicate is also a promise to the checker; an incorrect predicate can lie.
Narrow absent values and object variants where you use them
An optional field can be absent
interface Note { title: string; subtitle?: string }
function summary(note: Note): string {
return note.title + " / " + (note.subtitle ?? "none");
}
console.log(summary({ title: "Draft" }));
console.log(summary({ title: "Draft", subtitle: "" }));Output
Type check passed
Draft / none
Draft /Checked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
An absent optional property reads as undefined. Nullish coalescing preserves an intentionally empty string. With strict null checking, handle an optional value before using a method on it. The non-null assertion operator suppresses a check; it does not insert a runtime guard. Optional Chaining & Nullish Coalescing owns the JavaScript operators themselves.
Ignoring a possibly absent field fails the checker
function shout(note: { subtitle?: string }): string {
return note.subtitle.toUpperCase();
}Output
TS18048: 'note.subtitle' is possibly 'undefined'.Checked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
The discriminant connects a status to its available data
type Result = { kind: "ok"; value: number } | { kind: "failed"; message: string };
function show(result: Result): string {
if (result.kind === "ok") return "Value " + result.value;
return "Failed " + result.message;
}
console.log(show({ kind: "ok", value: 3 }));
console.log(show({ kind: "failed", message: "offline" }));Output
Type check passed
Value 3
Failed offlineChecked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
A discriminated union models alternatives without pretending that every field is always present. A switch can assign its remaining value to never in the default branch to catch an unhandled member. This checks the declared union, not arbitrary incoming JSON. Decode the external value first; an assertion such as JSON.parse(text) as Result skips that protection.
Structural types do not remove fields or freeze objects
A compatible object can carry additional runtime fields
interface PublicTask { title: string }
const stored = { title: "Draft", secret: "private" };
const view: PublicTask = stored;
console.log(view.title);
console.log(Object.keys(view).join(","));
console.log(view === stored);Output
Type check passed
Draft
title,secret
trueChecked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
Structural compatibility means that an object with the required fields can often be assigned to a smaller shape. A fresh object literal gets an extra-property check in contexts such as the next example. This is a helpful typo check, not a runtime allowlist. Pick and Omit also describe types; they do not copy or delete properties. Select fields into a new object when crossing a data boundary.
A fresh literal gets an excess-property check
interface PublicTask { title: string }
const view: PublicTask = { title: "Draft", secret: "private" };Output
TS2353: Object literal may only specify known properties, and 'secret' does not exist in type 'PublicTask'.Checked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
readonly prevents writes through that view, not through every alias
const source = { title: "Draft" };
const view: Readonly<{ title: string }> = source;
source.title = "Published";
console.log(view.title);
console.log(Object.isFrozen(view));Output
Type check passed
Published
falseChecked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
Readonly is checked at compile time and is shallow. Object.freeze is a separate JavaScript operation, also shallow unless nested objects are handled. Neither automatically clones the object. Deep Copy vs Shallow Copy & Data Structures owns copy boundaries; this lesson owns what the type annotation does and does not guarantee.
Use a generic when a type relationship must survive a call
Preserve the element type while admitting an empty array
function firstOrNull<T>(items: readonly T[]): T | null {
const first = items[0];
return first === undefined ? null : first;
}
const task = firstOrNull([{ title: "Draft" }]);
console.log(task === null ? "empty" : task.title);
console.log(firstOrNull<number>([]) === null);Output
Type check passed
Draft
trueChecked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
The generic links the input element type to the result type; returning any would lose that relationship. This helper chooses to treat an undefined first element as empty. That is a policy choice, so a different contract might return a tagged found/not-found result. Generics do not turn into runtime checks or manufacture a value of an arbitrary type.
Utility types build new compile-time shapes: Partial makes properties optional, Pick selects named properties, and Omit excludes named properties. Use them when the resulting API is meaningful. A Partial update still needs rules about allowed fields and which supplied values are valid. A declaration file describes a library contract; it can be wrong or stale and does not implement the library.
Guided exercise: validate before consuming
This exercise runs in the JavaScript editor so you can observe the runtime checks that remain after TypeScript is erased. Use the literal hints to supply the string check, trimming call and absent result. Start with unknown in the corresponding TypeScript version; after the string check, the checker permits trim.
function titleOf(value) {
if (typeof value !== ___) return null; // 👉 replace ___ with "string"
const title = value.___(); // 👉 replace ___ with trim
return title.length > 0 ? title : ___; // 👉 replace ___ with null
}
console.log(titleOf(" Draft "));
console.log(titleOf(12));
console.log(titleOf(" "));
// ✅ Expected output:
// Draft
// null
// nullThe same checks narrow an unknown TypeScript parameter
function titleOf(value: unknown): string | null {
if (typeof value !== "string") return null;
const title = value.trim();
return title.length > 0 ? title : null;
}
console.log(titleOf(" Draft "));
console.log(titleOf(12));
console.log(titleOf(" "));Output
Type check passed
Draft
null
nullChecked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
Changing only a return annotation cannot make an invalid value safe. Try removing the typeof guard in the TypeScript Playground, then read the diagnostic at the operation that needs a string. In the JavaScript editor, try a number and watch the explicit null result.
Brief: decode one task into an honest result
Write decodeTask(input: unknown). Accept a non-null, non-array object with an id consisting of a lowercase ASCII letter followed by up to 15 lowercase letters, digits or hyphens; a title containing 1 through 40 UTF-16 code units after trimming; and a boolean done. Check in that order. Do not coerce values. Ignore extra fields by returning a new record containing only id, trimmed title and done.
Return a discriminated result with kind ok and task, or kind invalid and a reason. Write describe with a switch and a never exhaustiveness check. Keep JSON syntax parsing separate; malformed JSON still throws before decoding. This contract is for ordinary decoded JSON data, not adversarial getter objects or proxies. It does not authorize access to a task, store it or make the record immutable.
Decode unknown data before claiming a Task type
type Task = { id: string; title: string; done: boolean };
type DecodeResult =
| { kind: "ok"; task: Task }
| { kind: "invalid"; reason: string };
function decodeTask(input: unknown): DecodeResult {
if (typeof input !== "object" || input === null || Array.isArray(input))
return { kind: "invalid", reason: "expected an object" };
if (!("id" in input) || typeof input.id !== "string" ||
!/^[a-z][a-z0-9-]{0,15}$/.test(input.id))
return { kind: "invalid", reason: "invalid id" };
if (!("title" in input) || typeof input.title !== "string" ||
input.title.trim().length < 1 || input.title.trim().length > 40)
return { kind: "invalid", reason: "invalid title" };
if (!("done" in input) || typeof input.done !== "boolean")
return { kind: "invalid", reason: "invalid done" };
return { kind: "ok", task: {
id: input.id, title: input.title.trim(), done: input.done
} };
}
function describe(result: DecodeResult): string {
switch (result.kind) {
case "ok": return result.task.id + ": " + result.task.title;
case "invalid": return "Invalid: " + result.reason;
default: {
const impossible: never = result;
return impossible;
}
}
}
const raw: unknown = JSON.parse('{"id":"task-a","title":" Draft ","done":false,"secret":"omit"}');
const good = decodeTask(raw);
console.log(describe(good));
console.log(describe(decodeTask({ id: "A", title: "Draft", done: false })));
console.log(describe(decodeTask({ id: "a", title: " ", done: false })));
console.log(describe(decodeTask({ id: "a", title: "Draft", done: "false" })));
if (good.kind === "ok") console.log(Object.keys(good.task).join(","));Output
Type check passed
task-a: Draft
Invalid: invalid id
Invalid: invalid title
Invalid: invalid done
id,title,doneChecked with the strict TypeScript compiler; successful emitted JavaScript is then run in Node. This panel is not the JavaScript editor.
The runnable block below is the compiler’s emitted JavaScript for that solution. Its runtime validation remains; interfaces, unions, annotations and the never check are erased. The separate TypeScript panel above verifies the static contract.
"use strict";
function decodeTask(input) {
if (typeof input !== "object" || input === null || Array.isArray(input))
return { kind: "invalid", reason: "expected an object" };
if (!("id" in input) || typeof input.id !== "string" ||
!/^[a-z][a-z0-9-]{0,15}$/.test(input.id))
return { kind: "invalid", reason: "invalid id" };
if (!("title" in input) || typeof input.title !== "string" ||
input.title.trim().length < 1 || input.title.trim().length > 40)
return { kind: "invalid", reason: "invalid title" };
if (!("done" in input) || typeof input.done !== "boolean")
return { kind: "invalid", reason: "invalid done" };
return { kind: "ok", task: {
id: input.id, title: input.title.trim(), done: input.done
} };
}
function describe(result) {
switch (result.kind) {
case "ok": return result.task.id + ": " + result.task.title;
case "invalid": return "Invalid: " + result.reason;
default: {
const impossible = result;
return impossible;
}
}
}
const raw = JSON.parse('{"id":"task-a","title":" Draft ","done":false,"secret":"omit"}');
const good = decodeTask(raw);
console.log(describe(good));
console.log(describe(decodeTask({ id: "A", title: "Draft", done: false })));
console.log(describe(decodeTask({ id: "a", title: " ", done: false })));
console.log(describe(decodeTask({ id: "a", title: "Draft", done: "false" })));
if (good.kind === "ok")
console.log(Object.keys(good.task).join(","));
// ✅ Expected output:
// task-a: Draft
// Invalid: invalid id
// Invalid: invalid title
// Invalid: invalid done
// id,title,doneThe task field types are useful to checked callers after the decoder succeeds. They do not replace the decoder. Add a new result member to the TypeScript union and the never assignment should fail until describe handles it. Deep Dive into JSON, Parsing & Serialization owns syntax parsing, revivers and JSON representation limits; Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns browser sinks and trust boundaries.
Practice quiz
What does this complete program print? const value="12";console.log(typeof value,value+1);
- string 121
- number 13
- string 13
- number 121
Answer: string 121. An erased assertion cannot convert a string; JavaScript still concatenates.
Which setting prevents this compiler configuration from emitting after a type error?
- strict alone
- noEmitOnError
- target ES2022
- module ESNext
Answer: noEmitOnError. Strict chooses checks; noEmitOnError controls emission when errors exist.
What must happen before reading a field from an unknown external value?
- Cast it to any
- Rename the interface
- Narrow or validate the value
- Remove strictNullChecks
Answer: Narrow or validate the value. unknown requires a justified operation; assertions do not validate incoming data.
What does this complete program print? const source={title:"A"};const view=source;source.title="B";console.log(view.title,Object.isFrozen(view));
- A true
- A false
- B true
- B false
Answer: B false. A readonly type view erases; aliasing and runtime mutability remain.
What does Omit<Task, "secret"> do by itself?
- Describes a compile-time shape
- Deletes secret at runtime
- Creates a frozen copy
- Validates JSON
Answer: Describes a compile-time shape. Utility types transform types, not runtime objects.
What does this complete program print? const value={subtitle:""};console.log(JSON.stringify(value.subtitle??"none"));
- "none"
- ""
- null
- undefined
Answer: "". Nullish fallback keeps an empty string.
What does this complete program print? const stored={id:"a",secret:"x"};const selected={id:stored.id};console.log(Object.keys(selected).join(","),selected===stored);
- id,secret true
- id true
- id false
- id,secret false
Answer: id false. Explicit field selection creates a separate object with only the chosen field.
Why include a never assignment after handling every declared union member?
- To validate arbitrary JSON
- To catch network failures
- To remove the default branch at runtime
- To reveal a newly unhandled member during checking
Answer: To reveal a newly unhandled member during checking. Exhaustiveness applies to the declared union; incoming values still need validation.
Continue this course
- Previous: Module Bundlers: Webpack, Parcel, Vite (Overview)
- Next: Testing JavaScript with Jest & Mocha — Write unit tests, mocks, and assertions with Jest and Mocha
- Quick reference: JavaScript cheat sheet