Skip to content
FrontDepth, Home

TypeScript

Structural typing and type erasure

What TypeScript is and what it is not: a type checker whose types are erased before the code runs, structural compatibility and excess property checks, interface vs type, any, unknown and never, the strict flags that matter, erasable syntax and branded types.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

No prerequisites.

This topic starts at Junior level.

JuniorConcept

What TypeScript is

TypeScript is JavaScript with type syntax added. Everything you know about JavaScript still holds: the same values, the same operators, the same runtime. TypeScript adds a way to describe those values, and a tool that reads the descriptions.

TypeScript
function greet(user: { name: string }): string {
  return `Hello, ${user.name}`;
}

greet({ name: "Ada" });
greet("Ada"); // error: Argument of type 'string' is not assignable to parameter of type '{ name: string; }'.

TypeScript does two separate jobs:

  1. Type checking. The type checker reads your code and reports the places where a value doesn't match its type. Your editor runs the same checker while you type; that is where the red underlines come from.
  2. Producing JavaScript. Browsers and Node run JavaScript, so the type syntax has to go. The types are removed, and what remains is ordinary JavaScript:
JavaScript
function greet(user) {
  return `Hello, ${user.name}`;
}

That removal is . The TypeScript handbook states it as a rule: type annotations never change the runtime behavior of your program.

Checking and stripping are different tools

tsc, the TypeScript compiler, does both jobs. Many tools do only the second: Node runs a .ts file directly by replacing the types with whitespace, and transpilers such as esbuild and Sucrase convert TypeScript to JavaScript one file at a time. They are fast because they never check types.

Shell
npx tsc --noEmit   # type-check the project, write no files
node server.ts     # strip the types and run; nothing is checked

Even tsc writes the JavaScript when it finds type errors, unless you turn on noEmitOnError. The handbook explains why: a project being migrated from JavaScript should keep running while you fix its types.

The practical consequence: a type error stops nothing by itself. A tool that only strips types runs the code anyway. Some frameworks run the checker as part of their build; otherwise the project needs its own type-check step, usually a tsc --noEmit script that runs in CI. And a red underline in the editor is a bug report, not a formality.

JuniorConcept

Types describe shapes

In Java or C#, a class fits a type only if its declaration says so (class Dog implements Pet). That is nominal typing: names and declarations decide. TypeScript works differently. A value fits a type when it has the members the type requires, with compatible types; where the value came from and what it is called don't matter. This is , and it matches how JavaScript is written: plain objects passed around and used for what they contain.

TypeScript
interface Point {
  x: number;
  y: number;
}

function length(p: Point): number {
  return Math.hypot(p.x, p.y);
}

const reading = { x: 3, y: 4, label: "sensor" };
length(reading); // OK: it has x and y

class Vector {
  x = 1;
  y = 2;
}
length(new Vector()); // OK: no "implements Point" needed

reading was never declared as a Point, and it has an extra label. It still fits, because everything Point asks for is there.

Assignability

TypeScript describes this with one word: assignable. A type A is assignable to B when a value of A can be used wherever a B is expected. Extra properties are fine. A missing property, or one of the wrong type, is an error:

TypeScript
interface User {
  name: string;
  age: number;
}

const draft = { name: "Ada" };
const user: User = draft;
// error: Property 'age' is missing in type '{ name: string; }'
// but required in type 'User'.

The rule goes beyond objects. A callback that takes fewer parameters than the caller passes is assignable too, which is why items.forEach((item) => ...) type-checks although forEach passes three arguments.

implements on a class asks TypeScript to check the class against an interface while you write it. It doesn't create a link that other code depends on: any object of the right shape still fits the interface.

So two types with the same shape are the same type for the checker, whatever their names. Usually that is what you want. When it isn't, for example a user id and an order id that are both strings, there are ways to make types behave nominally; the senior part of this topic covers them.

JuniorPitfalls

Excess property checks

Extra properties are allowed, except in one place. When you write an object literal directly where a type is expected, TypeScript checks it for properties the type doesn't have:

TypeScript
type DrawOptions = { color?: string; width?: number };

function draw(options: DrawOptions) {
  // ...
}

draw({ colour: "red", width: 100 });
// error: Object literal may only specify known properties, but 'colour'
// does not exist in type 'DrawOptions'. Did you mean to write 'color'?

This is the excess property check, and it applies only to fresh object literals: objects written right there, in an assignment, an argument or a return. Nothing else can refer to such an object, so a property the type doesn't know is almost always a typo. The handbook notes that most excess property errors are real bugs.

The same object stored in a variable first is not fresh, and passes:

TypeScript
const options = { colour: "red", width: 100 };
draw(options); // no error: "colour" is silently ignored

options is assignable to DrawOptions under the normal structural rule: it has width, and the optional color may be missing. The typo survives, and the line is drawn in the default color. Spreading an object into a literal ({ ...base }) doesn't check the spread object's extra properties either.

Types don't remove properties

The same rule explains a leak that surprises people. A narrower type hides properties from the checker, not from the program:

TypeScript
interface User {
  id: number;
  name: string;
  passwordHash: string;
}
type PublicUser = { id: number; name: string };

function toPublic(user: User): PublicUser {
  return user; // OK: User is assignable to PublicUser
}

const user: User = { id: 7, name: "Ada", passwordHash: "x9f2" };
const body = JSON.stringify(toPublic(user)); // still contains passwordHash

The return type says PublicUser, but the value is the whole user object, and JSON.stringify serialises everything it has. When only some fields may leave, in an API response, a log line or a message to the client, build a new object with exactly those fields: return { id: user.id, name: user.name };.

Don't silence an excess property error with an as assertion. Fix the typo, or fix the type if the property really belongs there.

JuniorPitfalls

Types don't exist at run time

Because types are erased, the running program can't see them. Three consequences catch people who are new to TypeScript.

You can't test a value against an interface. An interface or a type alias has no JavaScript counterpart, so there is nothing to compare with:

TypeScript
interface Admin {
  role: "admin";
  permissions: string[];
}

function isAdmin(value: unknown) {
  return value instanceof Admin;
  // error: 'Admin' only refers to a type, but is being used as a value here.
}

instanceof works with classes because a class is a JavaScript value, a constructor function, and instanceof checks the object's prototype chain at run time. For an interface you write the check yourself with JavaScript operations (typeof, in, Array.isArray, comparisons), and TypeScript learns from those checks. That is narrowing, the next topic.

An annotation is a promise, not a check. Nothing verifies data that comes from outside the program:

TypeScript
interface Product {
  title: string;
  price: number;
}

const product: Product = JSON.parse('{"title":"Kettle","price":"25"}');
const total = product.price + 5; // "255": price is a string at run time

JSON.parse returns any, so TypeScript accepts the annotation without question. The same is true of await response.json(), and anything read from localStorage, URL parameters or form fields starts as a plain string, whatever type you later claim for it. The compiler trusts what you write; the data doesn't care. Values from outside must be checked at run time, by hand or with a schema library; has its own topic.

You can't list a type's members. There is no way to ask, while the program runs, which properties Product has, for example to build a form or a table header. Go the other way: start from a value that exists at run time and derive the type from it.

TypeScript
const productFields = ["title", "price"] as const;
type ProductField = (typeof productFields)[number]; // "title" | "price"

The array exists in the JavaScript output and the type follows it, so the two can't drift apart.

The same holds for everything type-only: type, interface, generic parameters, as assertions and the ! operator all disappear. If a piece of code only tells TypeScript something, it does nothing when the program runs.

MiddleConcept

interface or type alias?

Both declarations name an object shape, and for most objects you can use either:

TypeScript
interface User {
  id: string;
  name: string;
}

type UserRecord = {
  id: string;
  name: string;
};

Thanks to structural typing, a value that fits one fits the other. The differences are in what else each can do.

A type alias can name any type. Unions, literal types, tuples, function types and types computed from other types (mapped and conditional types) need type:

TypeScript
type Status = "idle" | "loading" | "done";
type Pair = [string, number];
type OnSelect = (id: string) => void;

Interfaces merge. Two interface declarations with the same name in the same scope become one interface with the members of both. This is declaration merging, and it is how you add members to types you don't own, such as a browser global or a library's interface:

TypeScript
// globals.d.ts
interface Window {
  analytics?: { track(event: string): void };
}

// anywhere in the app
window.analytics?.track("page_view"); // type-checks

A second type with the same name is an error instead: "Duplicate identifier". The other side of merging is that it happens silently: two unrelated interface Config declarations in the same global scope combine without a warning.

extends reports conflicts; & hides them. An interface that redeclares an inherited property with an incompatible type fails at the declaration. An intersection with the same conflict compiles, and the property's type becomes never:

TypeScript
interface Base {
  id: string;
}

interface Broken extends Base {
  id: number; // error: Interface 'Broken' incorrectly extends interface 'Base'.
}

type Mixed = Base & { id: number }; // no error, but Mixed["id"] is never

The handbook makes the same point: the main difference between extending and intersecting is how conflicts are handled.

Which one to use

The handbook's heuristic is "use interface until you need to use features from type". Many teams do the opposite and use type everywhere, keeping interface for merging. Both are reasonable. What matters is that the codebase follows one convention, ideally enforced by a lint rule, so that a reader doesn't wonder whether the choice means something.

MiddleConcept

any, unknown and never

Three special types appear from the first week of TypeScript. The narrowing topic goes deeper into unknown; here is what each one means.

any switches the checker off. Every operation on an any value is allowed, any is assignable to every type, and whatever you read from it is any again:

TypeScript
const data: any = JSON.parse('"hello"');
data.toFixed(2); // compiles; throws a TypeError at run time
const n: number = data; // compiles; n holds a string

any spreads: one any from JSON.parse or response.json() flows through function calls and object properties into code that looks fully typed. TypeScript also falls back to any where it can't infer a type, such as an unannotated parameter; noImplicitAny turns that into an error: "Parameter 'a' implicitly has an 'any' type."

unknown accepts anything and allows nothing. Like any, every value is assignable to unknown. Unlike any, you can't use the value until you have checked what it is:

TypeScript
const input: unknown = JSON.parse('"hello"');
input.toUpperCase();
// error: 'input' is of type 'unknown'.

if (typeof input === "string") {
  input.toUpperCase(); // OK: the check proved it is a string
}

That makes unknown the honest type for anything you haven't checked yet: parsed JSON, a message from another window, a caught error.

never has no values. It is the return type of a function that never returns normally, because it always throws, and the type TypeScript gives a value once every possibility has been ruled out:

TypeScript
function fail(message: string): never {
  throw new Error(message);
}

never is assignable to every type, and no type except never itself is assignable to it. The second property is what exhaustiveness checks are built on: assign a value to never, and the compiler reports any case you forgot to handle.

Text
          accepts any value?    usable without a check?
any       yes                   yes (nothing is checked)
unknown   yes                   no
never     no (it has no values) -

A rule that serves well: use unknown at the edges where data enters, and treat every any in a diff as a decision someone has to explain.

MiddleConcept

Compiler flags that matter

How much TypeScript checks depends on tsconfig.json, and a few flags decide most of it:

JSON
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true
  }
}

strict turns on the whole strict family: noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, useUnknownInCatchVariables, alwaysStrict and strictBuiltinIteratorReturn. Since TypeScript 6.0, strict is on by default, but a project can still have it off, for example an older config with "strict": false or a project on an older TypeScript version. Check the config before you trust the types.

strictNullChecks catches the most bugs. Without it, null and undefined are allowed in every type, so the compiler can't tell you that a value may be missing. With it, they are separate types you must handle:

TypeScript
const root = document.querySelector("#app"); // Element | null
root.textContent = "Ready";
// error: 'root' is possibly 'null'.

const big = [1, 2, 3].find((n) => n > 5); // number | undefined

Each of those errors is a "Cannot read properties of null" that would otherwise happen at run time.

noImplicitAny stops the checker from quietly giving up: a parameter whose type can't be inferred becomes an error instead of any.

noUncheckedIndexedAccess is not part of strict. Without it, reading an array element or a record entry by index pretends the value is always there:

TypeScript
const scores: Record<string, number> = {};
const ada = scores["ada"]; // number, but undefined at run time

const names: string[] = [];
const first = names[0]; // string, but undefined at run time

With the flag, these become number | undefined and string | undefined, so you have to handle the missing case. It adds some noise (an indexed for loop needs a check too, while for...of doesn't), and it finds real bugs. exactOptionalPropertyTypes is another opt-in outside strict: with it, an optional color?: string may be left out, but { color: undefined } is an error unless the type includes undefined.

Turning strict on in an old codebase can produce hundreds of errors. Enable the flags one at a time, strictNullChecks first, and treat each error as a question: can this value really be missing here?

SeniorWeb platform

Syntax that does not erase

Almost all TypeScript syntax is type-only and disappears when it is stripped. A few older features are different: they produce JavaScript of their own.

TypeScript
enum Status {
  Active,
  Banned,
}

namespace Config {
  export const retries = 3;
}

class User {
  constructor(public name: string) {} // a parameter property
}

tsc compiles the enum into an object with name-to-number and number-to-name entries, the namespace into a function that fills an object, and the parameter property into a field plus this.name = name in the constructor. None of that can be produced by deleting characters, so a tool that only strips types can't handle it. Node's built-in type stripping refuses to start:

Text
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode

The same applies to import x = require("...") and export =. A namespace that contains only types is fine, because it erases completely. Transpilers such as esbuild and Sucrase do convert enums; the limit is specific to tools that only strip.

erasableSyntaxOnly

TypeScript 5.8 added the erasableSyntaxOnly flag. With it, tsc reports these constructs in the editor ("This syntax is not allowed when 'erasableSyntaxOnly' is enabled.") instead of letting you find out when the program fails to start. The release notes recommend combining it with verbatimModuleSyntax, which requires import type for imports that are only types. That matters for the same reason: a stripping tool sees one file at a time and can't know that an imported name is only a type. Node's documentation warns that without the type keyword it treats the import as a value import, which fails at run time.

The erasable replacements are ordinary JavaScript:

TypeScript
// Instead of an enum: an object and a union type derived from it
const Status = { Active: "active", Banned: "banned" } as const;
type Status = (typeof Status)[keyof typeof Status]; // "active" | "banned"

// Instead of a parameter property: a field and an assignment
class User {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

Instead of a namespace with values, use an ES module and its exports.

None of this makes enum wrong in a project built by tsc or by a transpiler that supports it. But type stripping in Node is stable since Node 25.2, and code written with erasable syntax works with every tool, strippers included.

SeniorExample

Nominal-like types with brands

Structural typing has one cost: two types with the same shape can't be told apart. Type aliases don't help, because an alias is only a new name for the same type:

TypeScript
type UserId = string;
type OrderId = string;

declare function cancelOrder(id: OrderId): void;
declare const userId: UserId;

cancelOrder(userId); // compiles: both are just string

When mixing such values up is a real risk (ids of different entities, amounts in different currencies, a string that has been validated and one that hasn't), you can make the types incompatible with a brand: an intersection with a property that exists only in the type.

TypeScript
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };

declare function cancelOrder(id: OrderId): void;
declare const userId: UserId;

function toOrderId(raw: string): OrderId {
  if (!/^ord_\d+$/.test(raw)) throw new Error(`Not an order id: ${raw}`);
  return raw as OrderId;
}

cancelOrder(toOrderId("ord_17")); // OK
cancelOrder("ord_17"); // error: Argument of type 'string' is not assignable to parameter of type 'OrderId'.
cancelOrder(userId); // error: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'.

A plain string lacks __brand, and the two brands have different literal types, so neither converts to the other. A branded value is still a string: it can go wherever a string is expected and has every string method.

The brand is pure type information. At run time the value is the original string, __brand doesn't exist, and nothing checks it. So the only as should sit inside a function like toOrderId that validates first: it is the one place where you tell the compiler "trust me", so make the claim true there. Brands don't survive serialisation either: ids that come back from JSON.parse or a server are plain strings and must pass through the same function again.

Classes offer a real nominal check. A class with a private or #private member is compatible only with its own instances and those of its subclasses, not with another class of the same shape, and #field in value tests for the class at run time:

TypeScript
class Cents {
  #value: number;
  constructor(value: number) {
    this.#value = value;
  }
  static is(x: object): x is Cents {
    return #value in x;
  }
}

Brands add a little ceremony where values are created. Use them where a mix-up would be expensive and hard to spot in review, not for every string in the codebase.

SeniorInterview tips

Interview tips

A 30-second answer. "TypeScript is JavaScript plus a type checker. Types are erased when the code becomes JavaScript, so they never change what the program does and never check data at run time. Compatibility is structural: a value fits a type when it has the required members, whatever its name, with one extra rule: fresh object literals are checked for unknown properties. tsc checks; Node's type stripping, esbuild or Sucrase only remove types, so the type check has to be its own step in CI."

Questions you are likely to get

  • Structural or nominal, and what is the difference? Show a class that fits an interface it never mentions, then mention brands as the way to get nominal behaviour.
  • Why does an object with an extra property fail here and pass there? Excess property checks apply only to fresh object literals.
  • Can you check at run time that a value is a User? Not from the interface: it is erased. Write a check with typeof and in, or use a schema; instanceof works only for classes.
  • interface or type? Unions and computed types need type; interfaces merge and report extends conflicts. Name your team's convention and why.
  • any or unknown? any disables checking; unknown forces a check before use.
  • Why does node app.ts reject this enum? Node only strips types; enums, namespaces with values and parameter properties need generated code. erasableSyntaxOnly reports them in the editor.

Mistakes that cost points

  • Saying TypeScript makes code "safe at run time" or validates API responses. It checks your code against your own claims; data from outside stays unchecked until you check it.
  • Treating a narrower return type as a filter. It hides properties from the checker, not from JSON.stringify.
  • Assuming a project is type-checked because it builds. Ask what runs tsc.
  • Reciting the strict family without knowing which flags matter most: strictNullChecks, noImplicitAny, and noUncheckedIndexedAccess, which strict does not include.

Senior signal

Talk about where types stop: the boundaries where data enters, the as and any that bypass the checker, the tsconfig flags that decide how much is checked, and the pipeline that decides whether it is checked at all. Show when you would introduce brands for ids or money in a large codebase, and what they cost: a validating function at every point where such values are created.

JuniorReview checklist

What to check when reviewing TypeScript types

Use this list when you review TypeScript you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. Type mistakes don't fail loudly: the code still becomes JavaScript and runs, and the wrong assumption shows up later as bad data or a crash in production.

  • Does something in CI run the type checker? Tools that only strip types (Node, esbuild, Sucrase) build and run code full of type errors. Look for tsc --noEmit, or a framework build that type-checks, in the pipeline; break a type on purpose once and confirm the pipeline fails.
  • Is data from outside annotated as if it had been checked? const user: User = await response.json() or JSON.parse(text) as Config is a promise nobody verifies. Look for annotations and as on parsed JSON, storage and URL values: they should stay unknown until a runtime check or a schema has validated them.
  • Does an object sent to an API, a log or JSON.stringify contain only the fields its type lists? A narrower type doesn't remove properties, so returning a whole User as a PublicUser sends everything. Check that such objects are built field by field, and look at the real payload in the network panel or the log.
  • Does the diff add any, as any, @ts-ignore or @ts-expect-error? Each one switches the checker off for a value or a line. Search the diff for them; each needs a reason in a comment, and unknown plus a check is usually possible instead.
  • Did tsconfig.json change? Turning off strict, strictNullChecks or noImplicitAny hides errors across the whole project, not just in the changed files. Read every change to the config and run tsc --noEmit with the old and the new settings.
  • Does the code use enum, a namespace with values or parameter properties where the project runs through type stripping? Node's built-in stripping fails on them at startup with ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX. Run the file with Node, or turn on erasableSyntaxOnly so that tsc reports them.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions