Introduction
Most data in a program lives in objects: a user, an order, a setting. An interface gives an object's shape a name, listing each property and its type, so that every function receiving such an object knows what it can use, and every place that creates one is checked for missing or misspelt properties.
How it works
An interface lists properties and their types:
interface Person {
readonly id: number;
name: string;
email?: string;
address: { city: string; postcode?: string };
}
- A property marked
?is optional: its type becomesstring | undefined, so you handle the missing case, for example withp.email ?? "none". - A readonly property can be set only when the object is made;
p.id = 5is an error. - Properties can hold other objects, written inline as above or as another interface.
An index signature describes an object used as a dictionary, with keys not known in advance: interface Scores { [subject: string]: number } accepts any string key whose value is a number. The built-in type Record<string, number> says the same more briefly.
TypeScript uses structural typing: a value fits a type if it has the required properties with the right types, whatever it is called or wherever it came from. An object with extra properties still fits, so a function asking for a Person will accept anything that has id, name and address.
There is one exception. When you write an object literal straight into a typed place, an extra property is an error (TS2353), because it is almost always a typo:
const p: Person = { id: 1, name: "Ada", adress: { city: "London" } };
// error TS2353: Object literal may only specify known properties, and 'adress' does not exist in type 'Person'.
You will also see object types written with type Person = { ... }. For objects, an interface and a type alias are nearly interchangeable; interfaces can be extended and merged, while type aliases can also name unions, which the next lesson covers.
Example
// An interface names the shape of an object.
interface Address {
city: string;
postcode?: string; // optional
}
interface Person {
readonly id: number; // can be set only when the object is made
name: string;
address: Address;
}
interface Scores {
[subject: string]: number; // an index signature: any key, number values
}
function label(p: Person): string {
const code = p.address.postcode ?? "no postcode";
return p.name + " (" + p.address.city + ", " + code + ")";
}
const ada: Person = { id: 1, name: "Ada", address: { city: "London" } };
const alan = { id: 2, name: "Alan", address: { city: "Wilmslow", postcode: "SK9" }, born: 1912 };
console.log(label(ada));
console.log(label(alan)); // alan has the shape of a Person, and more: that is allowed
const scores: Scores = { math: 90, physics: 75 };
scores["chemistry"] = 82;
let total = 0;
for (const subject in scores) total += scores[subject];
console.log(Object.keys(scores), total);Line by line
Addresshas an optionalpostcode;Personhas a readonlyidand a nestedAddress.labelreadspostcodewith??, because it may be missing.adais written straight into aPerson, so it is checked exactly.alanwas created without a type and has an extraborn; it still fitsPersonwhen passed tolabel.scoresuses an index signature, so a new subject can be added with any name.
Expected result
Ada (London, no postcode)
Alan (Wilmslow, SK9)
[ 'math', 'physics', 'chemistry' ] 247
In the real world
Interfaces describe API responses, database rows, component properties and configuration objects. Teams often keep them in shared files so that the code that sends data and the code that receives it agree. Because typing is structural, test code can pass simple object literals wherever a real object is expected, as long as the shape is right.
Common mistakes
- Reading an optional property as if it were always there; it may be undefined.
- Expecting readonly to freeze nested objects: it protects only that one property, not the object inside it.
- Using an index signature when the keys are known; listing them gives better checking and autocompletion.
- Being surprised that extra properties pass when an object comes from a variable rather than a literal.
Best practices
- Name the shapes your program passes around with interfaces.
- Make a property optional only when it really may be missing, and handle that case.
- Use
readonlyfor identifiers and values that must not change after creation.
Summary
Interfaces describe objects: their properties, which are optional (?), which are readonly, and, with an index signature, how a dictionary's values are typed. TypeScript checks shapes structurally, so any value with the needed properties fits, but an object literal with an unknown property is reported, which catches spelling mistakes early.
Quick check
Key takeaways
- An interface lists an object's properties; ? makes one optional and readonly fixes it after creation.
- TypeScript compares shapes, not names: anything with the right properties fits.
- Object literals are checked strictly for extra properties, which catches misspelt names.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.