Basic · 5 of 13 · 15 min read
Objects and interfaces
Describing the shape of an object, what optional and readonly really promise, and the excess property check that only fires on a literal.
- Objects
- Interfaces
An interface describes the shape of an object: what properties it has and what each one holds. Because the type system is structural, any value with that shape satisfies it — the name is for you, not for the compiler.
Declaring a shape
interface User {
id: number;
name: string;
email?: string; // optional
readonly createdAt: Date;
}
const user: User = {
id: 1,
name: "Ana",
createdAt: new Date(0),
};
console.log(user.email?.length ?? 0); // 0
// user.createdAt = new Date(); // Cannot assign to 'createdAt'
Nested shapes are checked just as thoroughly, and naming the inner one makes the errors readable:
interface Server { host: string; port: number }
interface Config { server: Server; debug?: boolean }
const config: Config = { server: { host: "localhost", port: 8080 } };
// const bad: Config = { server: { host: "x", port: "8080" } }; // string vs number
console.log(config.server.port, config.debug); // 8080 undefined
Optional means absent
interface User { id: number; email?: string }
const a: User = { id: 1 }; // fine
const b: User = { id: 1, email: "x" };
// const c: User = { id: 1, email: null }; // null is not string | undefined
// console.log(a.email.length); // 'a.email' is possibly 'undefined'
console.log(a.email?.length ?? 0); // 0
console.log("email" in a); // false
? says the property may be missing, and reading it gives string | undefined. It says nothing
about null — that has to be written out.
Under exactOptionalPropertyTypes, “absent” and “explicitly undefined” are distinguished, which
matters for a PATCH payload where clearing a field and not mentioning it are different requests:
// exactOptionalPropertyTypes: true
interface Patch {
name?: string; // may be absent
nickname?: string | undefined; // may be absent OR explicitly cleared
}
const a: Patch = {};
const b: Patch = { nickname: undefined };
// const c: Patch = { name: undefined }; // rejected with the flag on
console.log("nickname" in b); // true
readonly is one level and compile-time
interface Config {
readonly host: string;
readonly tags: string[];
}
const config: Config = { host: "localhost", tags: ["a"] };
// config.host = "other"; // Cannot assign to 'host'
config.tags.push("b"); // allowed — the array itself is not readonly
console.log(config.tags); // ["a", "b"]
// Both levels:
interface Locked { readonly tags: readonly string[] }
Exactly the shallowness of const on a binding, and of Object.freeze at runtime — except that
readonly emits nothing at all.
The excess property check
interface User { id: number; name: string }
const fromVariable = { id: 1, name: "Ana", extra: true };
const a: User = fromVariable; // fine
// const b: User = { id: 1, name: "Ana", extra: true };
// Object literal may only specify known properties
Structural typing says a wider value is assignable, so a is correct. The literal gets an extra
check on top, because nobody writes an undeclared property on purpose. Three honest ways through
it:
interface User { id: number; name: string }
// 1. Declare what you want:
interface UserWithExtra extends User { extra: boolean }
const a: UserWithExtra = { id: 1, name: "Ana", extra: true };
// 2. An index signature, when extra keys are genuinely expected:
interface Loose extends User { [key: string]: unknown }
const b: Loose = { id: 1, name: "Ana", extra: true };
// 3. `satisfies`, which checks without widening:
const c = { id: 1, name: "Ana" } satisfies User;
console.log(a.extra, b.extra, c.name);
Note what is not on that list: as User. It silences the check without doing anything else,
so a genuine typo survives.
Index signatures
interface Scores {
[player: string]: number;
// name: string; // 'string' is not assignable to 'number'
}
const scores: Scores = { ana: 10 };
scores.beto = 20;
const missing = scores.nobody; // typed number, actually undefined
console.log(missing); // undefined
Two costs. Every declared property has to satisfy the signature, and a missing key reads as the
value type rather than undefined — the same hole as array indexing, fixed by the same flag.
Record<Keys, Value> says the same thing more briefly, and with a known key union it is
exhaustive, which is usually what you want:
type Role = "admin" | "user" | "guest";
const permissions: Record<Role, string[]> = {
admin: ["read", "write", "delete"],
user: ["read", "write"],
guest: ["read"],
};
// Adding "owner" to Role makes this object a compile error until it is handled.
const loose: Record<string, string[]> = {};
console.log(permissions.guest, loose.anything); // ["read"] undefined
| Want | Use |
|---|---|
| A fixed, known set of properties | an interface |
| A dictionary with arbitrary string keys | Record<string, V> |
| An object with one entry per union member | Record<Union, V> |
| A shape plus arbitrary extras | an interface with an index signature |
Extending
interface User { id: number; name: string }
interface Timestamped { createdAt: Date }
interface Admin extends User, Timestamped {
permissions: string[];
}
const admin: Admin = {
id: 1,
name: "Ana",
createdAt: new Date(0),
permissions: ["all"],
};
function greet(user: User) { return user.name; }
console.log(greet(admin)); // "Ana" — an Admin is structurally a User
Multiple extension is allowed, unlike class inheritance. And extends checks as it goes: a
property redeclared with an incompatible type is an error at the declaration, which an
intersection would have let through.
Methods
interface Repository {
find(id: number): string | null; // method shorthand
onChange: (value: string) => void; // property holding a function
}
const repo: Repository = {
find: (id) => (id === 1 ? "Ana" : null), // parameter inferred
onChange: (value) => console.log(value),
};
console.log(repo.find(1)); // "Ana"
The two spellings differ in one detail: method shorthand has bivariant parameter checking for
historical reasons, while the property form is checked strictly under strictFunctionTypes. The
property form is the safer of the two for a callback.
Common mistakes
Reaching for as to silence a literal error
Mistake. const user = { id: 1, nmae: "Ana" } as User.
Why it fails. The assertion turns the check off, so the typo survives and user.name is
undefined at runtime.
What to do instead. Fix the property, or use satisfies User, which checks and keeps the
inferred type.
Expecting readonly to protect the contents
Mistake. readonly items: string[] and assuming nothing can change.
Why it fails. Only the property binding is protected; items.push(...) is untouched.
What to do instead. readonly items: readonly string[], and remember none of it exists at
runtime.
Using an index signature when the keys are known
Mistake. { [key: string]: string[] } for a fixed set of roles.
Why it fails. Every lookup appears to succeed, including the typo’d ones, and nothing forces
you to handle a new role.
What to do instead. Record<Role, string[]>, so adding a member to the union breaks the build.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does an index signature like [key: string]: number declare?
An interface can describe nested shapes, and the compiler checks every level.
Which part of this object fails to compile?
interface Config {
server: { host: string; port: number };
debug?: boolean;
}
const config: Config = {
server: { host: "localhost", port: "8080" },
};An object literal assigned straight to a typed target gets an extra check the compiler does not apply elsewhere.
Why is the second declaration an error while the first is fine?
interface User { id: number; name: string }
const fromVariable = { id: 1, name: "Ana", extra: true };
const a: User = fromVariable;
const b: User = { id: 1, name: "Ana", extra: true };What does the ? in email?: string declare?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.