../courses.php
TypeScript
TS104
3
Interfaces Create Contracts
Interfaces describe the shape an object is expected to have.
What does an interface do?
An interface creates a contract for an object by listing the property names and value types that the object should contain.
Objects often carry related data.
In JavaScript, the expected object shape may be unclear.
TypeScript interfaces make the expected shape visible.
This helps teams agree on what data should look like.
An interface is like a contract between code that sends data and code that uses data.
A user interface
interface User {
id: number;
email: string;
active: boolean;
}
const user: User = {
id: 7,
email: "maya@example.com",
active: true
};
interface User names the expected object shape.
id must be a number.
email must be a string.
active must be a boolean.
The object assigned to User must follow that contract.
Shape
Interfaces describe object structure.
Contracts
Code can agree on required data.
Teams
Developers can understand shared objects faster.
Safety
Missing or wrong properties are easier to catch.
Unclear object
const user = {
id: "seven",
email: true
};
Object follows interface
const user: User = {
id: 7,
email: "maya@example.com",
active: true
};
Ask ChatGPT: "Does this object satisfy the TypeScript interface? List missing or wrong properties."
Create a User interface.
Add id, email, and active properties.
Create an object that follows the interface.
Create one object that breaks the interface.
Explain why interfaces are contracts.
Thinking interfaces create runtime objects.
Using the wrong property type.
Forgetting required properties.
Making interfaces vague.
Ignoring object shape.
Use interfaces to describe object shapes and create safer contracts.
Login - Jit4All
Login
Welcome back to Jit4All