Sub topic 1
Object Types and Their Properties
This chapter covers the base that optional and readonly modifiers build on: how TypeScript describes the shape of an object, what a property is in that description, and how the compiler decides whether a value fits a shape. The later chapters add ? and readonly to these shapes, so the rules here apply to everything that follows.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript syntax and type annotations such as
let n: number. - How to declare interfaces and type aliases.
- Union types, including
undefined(for examplestring | undefined). - How JavaScript objects and arrays work: property access with
.and[], and object literals.
You do not need to know classes, generics or mapped types yet. They appear briefly in later chapters.
What an object type describes
An object type is a list of property names and the type of each one. TypeScript uses it to check two things: that a value has the properties your code reads, and that those properties hold the right kinds of values.
You can write an object type in three places.
// 1. Inline, directly in an annotation
let point: { x: number; y: number } = { x: 1, y: 2 };
// 2. As an interface
interface User {
id: number;
name: string;
}
// 3. As a type alias
type Product = {
sku: string;
price: number;
};
const u: User = { id: 1, name: "Ada" };
const p: Product = { sku: "A-100", price: 9.5 };
console.log(point.x, u.name, p.price);For describing a plain object, interface and type behave the same in nearly every case. Everything in this tutorial works with either. Pick the style your codebase already uses.
Each entry in the list is a property signature: a name, a colon and a type. You can separate entries with ; or ,. Most style guides use semicolons.
Properties are required by default
A property written without any modifier is required. A value assigned to the type must have it, and the value must have the declared type.
interface User {
id: number;
name: string;
}
// const missing: User = { id: 1 };
// Error: Property 'name' is missing in type '{ id: number; }'
// but required in type 'User'.
// const wrong: User = { id: "1", name: "Ada" };
// Error: Type 'string' is not assignable to type 'number'.This is the behavior the ? modifier changes in the next chapter. Keep the default in mind: without a modifier, "absent" is a type error.
Reading a property you did not declare is also an error.
interface User {
id: number;
name: string;
}
function show(user: User): void {
console.log(user.name);
// console.log(user.email);
// Error: Property 'email' does not exist on type 'User'.
}Reading and writing properties
By default, every property in an object type can be both read and written. Writing is checked against the declared type.
interface Counter {
label: string;
count: number;
}
const c: Counter = { label: "clicks", count: 0 };
c.count = c.count + 1; // OK
// c.count = "many"; // Error: Type 'string' is not assignable to type 'number'.The readonly modifier, covered later, is what removes the ability to write. Until then, assume any property can be assigned to.
Note that const c does not make the properties constant. const stops you from reassigning the variable c. It says nothing about what is inside the object. This difference between a binding and a value comes up again with readonly and as const.
Property names
Most property names are plain identifiers. Other names are also allowed.
interface Headers {
"content-type": string; // quoted name, needed because of the hyphen
42: boolean; // numeric name
[Symbol.iterator]?: never; // see note below
}The last line is only an illustration of the syntax. Computed names in types must be unique symbol or literal types, so for everyday work you will use identifiers, quoted strings and numbers. Here is a version you can compile as written.
interface Headers {
"content-type": string;
42: boolean;
}
const h: Headers = { "content-type": "text/html", 42: true };
console.log(h["content-type"], h[42]);Names with hyphens or spaces need bracket access (h["content-type"]). Dot access only works for valid identifiers.
Methods as properties
A function stored on an object is also a property. TypeScript offers two syntaxes.
interface Logger {
log(message: string): void; // method syntax
warn: (message: string) => void; // property with a function type
}
const logger: Logger = {
log(message) {
console.log("log:", message);
},
warn: (message) => {
console.log("warn:", message);
},
};
logger.log("a");
logger.warn("b");Both can be marked optional or readonly like any other property. One difference matters for strict checking: under strictFunctionTypes, parameters of a property with a function type are checked more strictly than parameters of a method. For now it is enough to know that both forms are properties of the object type.
Structural typing: shape decides compatibility
TypeScript checks objects by their shape, not by the name of the type. A value fits a type if it has at least the required properties with compatible types. This is called structural typing.
interface Named {
name: string;
}
const dog = { name: "Rex", legs: 4 };
const n: Named = dog; // OK: dog has a string 'name'. Extra properties are allowed here.
console.log(n.name);dog was never declared as Named, and it has an extra legs property. It still fits, because it has everything Named asks for.
Structural typing explains most of the behavior in the rest of the tutorial. In particular, the chapter on assignability shows that readonly is not part of the shape comparison, so it does not block assignment.
Excess property checks
There is one place where extra properties are rejected. When you write an object literal directly where a type is expected, TypeScript runs an excess property check. It assumes that an unknown name in a fresh literal is probably a typo.
interface Named {
name: string;
}
// const a: Named = { name: "Rex", legs: 4 };
// Error: Object literal may only specify known properties,
// and 'legs' does not exist in type 'Named'.
const extra = { name: "Rex", legs: 4 };
const b: Named = extra; // OK: not a fresh literal, so no excess property check
console.log(b.name);The check applies only to fresh object literals. Once the value is stored in a variable, it is no longer fresh. This check matters later because it is one reason optional properties catch misspelled names: if you write emial where email? is declared, the excess property check reports it.
interface Contact {
name: string;
email?: string;
}
// const c: Contact = { name: "Ada", emial: "[email protected]" };
// Error: Object literal may only specify known properties,
// but 'emial' does not exist in type 'Contact'. Did you mean 'email'?Weak types
An object type whose properties are all optional is called a weak type. TypeScript adds one extra rule for it: you cannot assign a value that shares no properties with the type.
interface Options {
verbose?: boolean;
retries?: number;
}
const opts = { colour: "red" };
// const o: Options = opts;
// Error: Type '{ colour: string; }' has no properties in common with type 'Options'.Without this rule, any object at all would fit Options, since nothing is required. You will meet weak types again whenever you use Partial<T>.
Index signatures
When you do not know the property names in advance, an index signature describes the key type and the value type.
interface Scores {
[player: string]: number;
}
const scores: Scores = { ada: 10, grace: 12 };
scores.linus = 7; // OK: any string key with a number value
// scores.alan = "high"; // Error: Type 'string' is not assignable to type 'number'.
console.log(scores["ada"]);Reading scores["nobody"] is typed as number, even though at runtime it is undefined. TypeScript does not add undefined to index reads by default. The noUncheckedIndexedAccess compiler option adds it. This is a close cousin of the optional-property problem you will see in the next chapter.
Property types and `undefined`
A required property whose type includes undefined is still required. The key must be present in the literal, even though its value can be undefined.
interface Row {
id: number;
note: string | undefined;
}
const ok: Row = { id: 1, note: undefined };
// const bad: Row = { id: 1 };
// Error: Property 'note' is missing in type '{ id: number; }' but required in type 'Row'.Keep this contrast in mind. The next chapter explains how note?: string differs from note: string | undefined.
Common errors at this stage
| Symptom | Cause | Fix |
|---|---|---|
| `Property 'x' is missing in type` | A required property is absent from the value | Add it, or declare the property optional if absence is valid |
| `Property 'x' does not exist on type` | You read a name the type does not declare | Fix the typo or add the property to the type |
| `Object literal may only specify known properties` | Excess property check on a fresh literal | Remove the extra name, or assign through a variable if the extra data is intended |
| `has no properties in common with type` | Weak type check | Provide at least one declared property |
| `Type 'string' is not assignable to type 'number'` | The value has the wrong type | Correct the value or the declared type |
How the pieces fit together
Summary
- An object type lists property names and their types. Write it inline, with
interface, or withtype. - Properties are required and writable unless a modifier says otherwise.
- Typing is structural. A value fits if it has the needed properties, and extra properties are allowed except in fresh object literals.
- Weak types, where every property is optional, reject values that share nothing with them.
- A required property typed
T | undefinedmust still be present.
Exercise
Given interface Point { x: number; y: number }, which of these lines compile? (a) const a: Point = { x: 1, y: 2, z: 3 }; (b) const tmp = { x: 1, y: 2, z: 3 }; const b: Point = tmp; (c) const c: Point = { x: 1 };
Show answer
Only (b) compiles. Line (a) fails the excess property check because z is not in Point and the value is a fresh object literal. Line (b) passes because tmp is a variable, not a fresh literal, and it has the required x and y. Line (c) fails because the required property y is missing.
Exercise
What is the difference between interface Row { note: string | undefined } and requiring that note be present? Write a value of type Row that compiles and one that does not.
Show answer
They are the same thing: a required property of type string | undefined must be present as a key, but its value may be undefined. { id: 1, note: undefined } compiles (with id: number also declared), and { id: 1 } does not, because note is missing.