Skip to content

Structural Contracts

The Course
•
25 min study

This course builds on TypeScript beginner: unions, narrowing, readonly records, small generics, unknown-data validation and the local project. Days 5–7 also use JavaScript promises, async/await and injected service dependencies. JavaScript advanced is not required. Refresh those linked topics before Day 5 if needed.

Our goal is a typed catalogue boundary: external values become validated books, a typed transport supplies data, and a reducer ignores stale completions. The compiler will enforce relationships, while runtime checks enforce data truth and timing.

Structural compatibility means a value may have more fields than a parameter asks for. Returning it under a smaller type does not remove those fields. If a public view must exclude secret data, construct a new object with only allowed properties. Assertions and Pick are not sanitizers. First predict the key difference below; it is the same distinction behind the corrected update exercise in beginner.

Predict, run, and explain

Write down what the program prints before you run it. Use Check types first; the program runs only when the real compiler accepts it.

Predict, then runTypeScript
type User = {
  id: string;

  name: string;

  secret: string;
};

type PublicUser = Pick<User, "id" | "name">;

const user: User = { id: "u1", name: "Ada", secret: "private" };
const merelyTyped: PublicUser = user;
const projected: PublicUser = { id: user.id, name: user.name };

console.log(Object.keys(merelyTyped).join(","));
console.log(Object.keys(projected).join(","));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
id,name,secret
id,name

Read the compiler error

Read the property mismatch. Structural compatibility still requires each promised field to have a compatible type.

Find and fix the type errorTypeScript
type User = {
  id: string;

  name: string;
};

const user: User = { id: "u1", name: 25 };

console.log(user);

Enable JavaScript to edit and type-check this example.

Check your diagnosis

Use a string name, or intentionally change the domain contract. Casting would not turn a number into text.

Type compatibility and data projection are separate contracts

Structural compatibility lets a richer value pass through a narrower interface. That is useful for reusable functions, but it does not filter the runtime object. If a caller must not receive internal fields, create a new public record rather than returning the original under a smaller annotation.

Ownership is another independent promise. A new outer object can still share nested data. State whether a public function returns a view, a shallow projection or an isolated snapshot, and test the actual keys and references that promise covers.

A smaller type keeps the secret fieldTypeScript
type Public = { title: string };

const source = { title: "Types", secret: true };

function view(value: Public): Public {
  return value;
}

console.log(Object.keys(view(source)).join(","));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
title,secret

The function has a valid parameter and return type. It still returns the original object, including data the public annotation does not expose through ordinary property access.

Projection builds a new public objectTypeScript
type Public = { title: string };

const source = { title: " Types ", secret: true };

function project(value: Public): Public {
  return { title: value.title.trim() };
}

const result = project(source);

console.log(Object.keys(result).join(","));
console.log(source.title === " Types ");

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
title
true

The body implements projection and normalization while leaving the source unchanged. The smaller alias alone implemented neither behavior.

Try the rule on new inputs

Test a source with extra fields and a padded title. Compare returned keys, source values and object identity. Explain which checks remain necessary even when the public return annotation is correct.

Debug a plausible mistake

Exercise

Repair a public projection

The public runtime object must contain only id and title, printing id,title. Preserve the internal object and its token. Merely assigning a narrower type must not be used as a sanitizer.

Predict the supplied program's actual behavior first. It compiles, but violates the requirement. Make a small repair, then try a case that would distinguish the repaired version from the original.

Debugging workspaceTypeScript
type PublicBook = { id: number; title: string };
const internal = { id: 1, title: "Read", token: "private" };
const publicBook: PublicBook = internal;

console.log(Object.keys(publicBook).join(","));

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

Structural compatibility does not delete extra fields from a JavaScript object.

Hint 2: a first step

Construct a new value with the explicitly allowed properties.

Show one solution
TypeScript
type PublicBook = { id: number; title: string };
const internal = { id: 1, title: "Read", token: "private" };
const publicBook: PublicBook = { id: internal.id, title: internal.title };

console.log(Object.keys(publicBook).join(","));
Text
id,title

The original compiled because internal has every field PublicBook requires; structural typing allows the extra token. The only evidence of the leak was runtime: Object.keys printed id,title,token. Building a new object literal is what removes the token, and because it is a fresh literal, adding token: internal.token to it would now be rejected as an excess property.

Your turn

Exercise

Structural Contracts: practice

Now look at structural contracts from the consumer's side. A Book has id, title and pages; a Course has code, title and lessons. Write one function, heading, that uppercases the title of either, with a parameter type that asks only for what heading uses. Call it with a Book variable and a Course variable and print TYPES and REACT. Then add a call with the fresh literal { title: "X", pgs: 3 } and read why that one is rejected.

Your workspaceTypeScript
// Define Book and Course, a small parameter type for heading, and two calls.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

Neither Book nor Course is the right parameter type: each would reject the other. Ask which single property the body reads.

Hint 2: a first step

Declare type Titled with only that property, then annotate the two records as Book and Course in separate variables before passing them.

Show one solution
One possible solutionTypeScript
type Book = { id: string; title: string; pages: number };
type Course = { code: string; title: string; lessons: number };
type Titled = { title: string };

function heading(item: Titled): string {
  return item.title.toUpperCase();
}

const book: Book = { id: "b1", title: "Types", pages: 120 };
const course: Course = { code: "R1", title: "React", lessons: 30 };

console.log(heading(book));
console.log(heading(course));

Enable JavaScript to edit and type-check this example.

Text
TYPES
REACT

Titled is the consumer's contract: heading needs a string title and nothing else, so both a Book and a Course satisfy it without sharing a declared type. heading({ title: "X", pgs: 3 }) is rejected with TS2353 because a fresh literal with an unknown property is probably a typo; the book variable's extra pages field is allowed, because it is real data. Inside heading, pages and lessons are still there at runtime, just invisible to the checker.

Change it and test it

Change the implementation to return book directly: it still type-checks, but the key expectation should fail. Restore projection. Explain why external JSON must be validated separately even if its caller-facing type looks correct.

Was this article helpful?

Your response is saved on this device.