Interfaces
A named description of the properties an object must have and the type of each.
What is it?
Most real data is an object with several properties, like a user with a name, email and age. Writing that shape out inline everywhere gets repetitive, and nothing ties the copies together as "the same shape."
An interface gives the shape a name, once. You list the properties and their types, then reuse the name everywhere. If an object is missing a required property, has one with the wrong type, or doesn't match where the shape is expected, TypeScript flags it immediately.
Explain like I'm 10
An interface is like a form with labeled blanks: "Name: ___, Email: ___, Age: ___." You must fill every required blank with the right kind of answer. You can't skip the email, or write your age as "twenty" instead of a number.
Examples
Defining and using an interface
interface User {
name: string;
email: string;
age: number;
}
const user: User = {
name: "Kai",
email: "kai@example.com",
age: 27,
};
function greet(user: User): string {
return `Hello, ${user.name}!`;
}User describes the shape once. The user variable and the greet function both reuse it, so every User is checked against the same definition.
Optional properties and readonly
interface Product {
readonly id: string;
name: string;
discountCode?: string; // optional — may or may not be present
}
const item: Product = { id: "p-1", name: "Mug" }; // valid, discountCode omitted
item.id = "p-2";
// Error: Cannot assign to 'id' because it is a read-only property.A ? after a property name makes it optional, so objects without it are still valid. readonly lets a property be set once but never reassigned.
How it works
An interface produces no JavaScript. It exists only at compile time, as a description the compiler checks objects, parameters and variables against.
When you annotate a value with an interface, TypeScript compares its properties to the ones the interface requires and flags anything missing or mismatched. After compiling, the interface is discarded and leaves no trace in the .js output.
Why does it exist?
Without a name, every function expecting "an object with a name, email and age" would spell the shape out inline, with no guarantee two copies mean the same thing. An interface gives the shape one reusable, checkable name, so intent is clearer and mistakes are caught consistently.
When to use it
Use an interface whenever you describe an object's shape: object parameters, API responses, component props, or any structure you reuse.
When not to use it
For something that isn't an object shape, like a union of strings, a function type or a primitive alias, a type alias (covered next) usually fits better. Interfaces are for "objects with named properties."
Common mistakes
Forgetting the
?on a property that's really optional, forcing every object to include it.Assuming
readonlyprotects the object at runtime. It's a compile-time check only; plain JavaScript or an unsafe cast can still change the value.Repeating the same object shape inline in several places instead of naming it once as an interface.
Practice exercises
- Easy:
Write an interface
Bookwithtitle: string,author: stringandpages: number, then create an object that satisfies it. - Medium:
Add an optional property
isbn?: stringtoBook, then create two validBookobjects: one with an ISBN and one without. - Hard:
Write a function
printSummary(book: Book): stringthat returns a formatted string. Add areadonlyproperty toBookthat would cause a compiler error if the function tried to change it.
Interview questions
What is an interface used for in TypeScript?
Naming and reusing an object's shape (its required properties and their types) so the compiler can check objects against it consistently.
Does an optional property (`prop?: type`) allow the property to be `undefined`, or does it allow the property to be omitted entirely?
Both. It can be left out of the object, or included and set to undefined.
Do interfaces exist at runtime in the compiled JavaScript?
No. Interfaces are compile-time only and produce no runtime code.
What is *structural typing*, and how does it relate to how interfaces are checked?
TypeScript compares types by shape (which properties exist and their types), not by name. Any object with the right properties satisfies an interface, whether or not it was ever annotated with that interface's name.
Given `interface User { name: string } const obj = { name: "Kai", age: 5 }; const u: User = obj;`, does this compile, even though `obj` has an extra `age` property?
Yes. obj is an existing variable, not a fresh object literal, so TypeScript only checks that it has at least the properties User requires. Extra properties are allowed.
Why does `const u: User = { name: "Kai", age: 5 };` fail to compile, when assigning the equivalent object through a variable (as in the previous question) does not?
This is the excess property check. Object literals written right at the assignment are checked more strictly, because an extra property there is usually a typo or a misunderstanding of the shape. The check doesn't apply to an object already stored in another variable.
Does marking a property `readonly` on an interface prevent it from ever being changed, even by plain JavaScript or a type assertion?
No. readonly is compile-time only. TypeScript rejects direct reassignment, but a type assertion or unchecked code can still change it at runtime, since nothing of the restriction remains in the compiled JavaScript.
If `discountCode?: string` is declared on an interface, what is its type inside code that has already confirmed the object has it?
string. Optional means "string, or absent/undefined", and once you check (for example if (item.discountCode)) TypeScript narrows string | undefined to string.
Can two objects that were never declared with the same interface name still both satisfy that interface?
Yes. Interfaces check structure, not identity, so any object with matching property names and types satisfies it, however it was created or annotated.
What happens if you declare `interface User { name: string }` a second time later in the same scope, adding `interface User { age: number }`?
TypeScript merges them into one interface with both name and age. This is declaration merging, and only interfaces support it. A duplicate type alias name is a compile error.
How would you make one interface build on another, like an `Admin` that has everything a `User` has plus a `permissions` field?
interface Admin extends User { permissions: string[] }. extends copies in every property from User, so an Admin must satisfy all of User plus the new field.
Can an interface describe a property whose key names aren't known in advance, like an object being used as a dictionary?
Yes, with an index signature: interface Scores { [username: string]: number } describes an object where every key is a string and every value a number, however many keys there are.
Can an interface property hold a function, and if so, how is it typed?
Yes. interface Logger { log: (message: string) => void } requires log to be a function taking a string and returning nothing. Any function assigned to log is checked against that signature.
If an interface property's type is itself another interface, like `interface Order { customer: User }`, how deep does TypeScript's checking go?
All the way down. Nested shapes are checked recursively, so customer must satisfy every requirement of User, not just be present.
Why does defining the same object shape inline in several different function signatures tend to cause problems over time?
Nothing ties the copies together. If the shape changes, say a new required field, you must update every copy by hand, and they easily drift apart. A named interface gives you one place to update.
Is it valid to have a required property listed after an optional one in an interface, like `interface Item { discount?: number; name: string }`?
Yes. Unlike function parameters, interface properties are matched by name, not position, so order doesn't matter.
What would happen if you forgot the `?` on a property that's genuinely sometimes absent, like writing `discountCode: string` instead of `discountCode?: string`?
Every object would have to include discountCode. Objects that legitimately have none would fail, forcing callers to invent placeholder values just to satisfy the compiler.
When would a type alias be a more natural fit than an interface for describing something?
When the thing isn't "an object with named properties": a union of allowed values, a tuple or a function signature. A type alias can express those directly; an interface can't.
Does an interface itself appear anywhere in the compiled `.js` output?
No. It's only used for checking during compilation, then discarded. No runtime object, class or value corresponds to it.
If a function parameter is typed with an interface, what happens if you call the function with an object missing one required property?
TypeScript reports a compile error at the call site naming the missing property. The mismatch is caught before the code runs.
Scenario: you want a `Config` interface where `apiUrl` is required but `timeout` should fall back to a sensible number if the caller doesn't provide it. Does the interface itself supply that fallback?
No. timeout?: number only says the property may be absent. You still write the fallback yourself where the object is used, such as config.timeout ?? 5000.
Why are interfaces particularly well suited to describing the props a UI component accepts?
Props are almost always a plain object with a fixed set of named fields, some required and some optional. That's exactly what interfaces describe, so a missing or mistyped prop is caught at the call site instead of at render time.