Intermediate · 14 min
Composing object types
Extend a shared interface and combine independent object requirements.
Extend shared fields
Use extends when a new interface adds fields to an existing contract. An extending interface must keep inherited properties compatible. This lets related records share a common identity without repeating its definition.
interface Identified { id: number }
interface Member extends Identified { name: string }
const member: Member = { id: 4, name: "Ada" };
console.log(member.id + ": " + member.name);Output
4: Ada
Require both shapes
An intersection combines requirements with &. A value must satisfy both sides. Conflicting property types do not become alternatives: a property required to be both string and number cannot hold an ordinary value. Use a union when you intend alternatives.
type Named = { name: string };
type Located = { city: string };
type Contact = Named & Located;
const contact: Contact = { name: "Leo", city: "Rome" };
console.log(contact.city);Output
Rome
Put it into practice
- Read the types and predict the output before running the examples.
- Fix the task without using "any" or a type assertion, then check both practice questions.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Complete a contact
Add the missing "city" property to "contact" with the value "Oslo". Keep the intersection type and display the city.
An intersection requires the properties from both types. Supply the missing field.
Show solution
type Named = { name: string };
type Located = { city: string };
const contact: Named & Located = { name: "Ada", city: "Oslo" };
const city = contact.city;
console.log(city);The value must satisfy both Named and Located. Adding the city fixes the missing-property error while preserving the original contract.