In the previous lesson the object's shape was written right next to the variable: { name: string; age: number }. For one variable that's fine. But as soon as there's a second variable, then a function that also takes a user, you're writing the same shape again and again. If you add one property, every copy has to change.
An interface gives that shape a name, like User. You write the shape once, then use the name in many places. One interface can also be the base of another, similar one: an Admin is a User with one more property, role.
Giving an object's shape a name
The interface User below is used by two variables:
interface User {
name: string;
age: number;
}
const budi: User = { name: "Budi", age: 17 };
const ani: User = { name: "Ani", age: 20 };
interface User { ... }makes a type namedUser. Its name starts with a capital letter, because that's the usual habit in TypeScript for type names.- Inside it, one property per line:
name: string;. const budi: Useruses that name like any other type. The shape is written once, then used many times.- The error messages get shorter too, because the type is called by its name,
User.const budi: User = { name: "Budi" };is rejected withProperty 'age' is missing in type '{ name: string; }' but required in type 'User'. ts(2741).
An interface as a parameter's type
The function formatUser below takes a User and returns one sentence:
function formatUser(user: User): string {
return user.name + " (" + user.age + ")";
}
console.log(formatUser(budi)); // Budi (17)
console.log(formatUser({ name: "Ani", age: 20 })); // Ani (20)
user: User: the parameter uses the named type, so you don't need to write{ name: string; age: number }again.- The sentence is joined from four pieces:
name, then" ("(a space and an opening parenthesis), thenage, then")". - Inside the function, TypeScript knows
user.nameis astringanduser.ageis anumber.user.roleis rejected:Property 'role' does not exist on type 'User'. ts(2339).
An interface exists only for TypeScript. In the compiled JavaScript, interface User is gone completely, not a single line of it is left:
"use strict";
function formatUser(user) {
return user.name + " (" + user.age + ")";
}
In the exercise, type User = { name: string; age: number }; is accepted too. How that differs from an interface is covered in the next lesson, Type Alias.
Optional properties in an interface
The interface User below has a third property, email, marked with a ?:
interface User {
name: string;
age: number;
email?: string;
}
Just like in an object type, ? lets email be missing. If you remove the email? line from the interface, an object that has an email is rejected: Object literal may only specify known properties, and 'email' does not exist in type 'User'. ts(2353).
extends: an interface built on another
Admin below is made from User, then used by two variables:
interface Admin extends User {
role: string;
}
const sari: Admin = { name: "Sari", age: 25, role: "editor" };
console.log(formatUser(sari)); // Sari (25)
const rina: Admin = { name: "Rina", role: "editor" };
extends UsermeansAdmininherits (gets a copy of) every property ofUser, then addsrole. So an Admin hasname,ageandrole.sarican be sent toformatUser, whose parameter has the typeUser, because an Admin has every property a User needs.rinais rejected:Property 'age' is missing in type '{ name: string; role: string; }' but required in type 'Admin'. ts(2741). Properties inherited fromUserare still required, even though they aren't written again inAdmin.
📌 Interfaces with the same name are merged
The code below makes two interfaces with the same name, User:
interface User {
name: string;
}
interface User {
age: number;
}
const budi: User = { name: "Budi" };
Two interfaces with the same name don't cause an error. TypeScript merges them into one User holding name and age (declaration merging). So budi is rejected for having no age. Libraries (ready-made code you install in a project) use this to add properties to an interface that already exists. In your own code, an accidental duplicate name can be confusing, so use different names.
⚠️ Interface written, exercise still red?
- No named type. This exercise checks that your code has an
interfaceor atypewhose name starts with a capital letter, likeinterface User.interface user(lowercase) doesn't count. - Writing the shape out again in the parameter.
function formatUser(user: { name: string; age: number })is valid, but the point of this lesson is to use the name:user: User. - The sentence's format. The result must be exactly
Budi (17): one space before the opening parenthesis, and no spaces inside the parentheses. Takenameandagefrom the parameteruser, because in the exerciseformatUseris also tested with{ name: "Ani", age: 20 }. - Thinking an interface exists while the code runs. An interface is gone after compiling. So data from a server isn't checked against
User.
TL;DR: interface User { name: string; age: number; } gives an object's shape a name. The name starts with a capital letter, and you use it like any other type: const budi: User, function formatUser(user: User): string. email?: string makes a property optional. interface Admin extends User { role: string; } inherits every property of User and adds role, and those inherited properties are still required. Two interfaces with the same name are merged into one. An interface is gone completely from the compiled JavaScript.
⚡ Give an object's shape a name
Write:
interface User {
name: string;
age: number;
}
const budi: User = { name: "Budi", age: 17 };
Meaning: An interface gives a name to an object's shape: its properties and the type of each. interface User makes a type called User, starting with a capital letter. The shape is written once, then its name is used in many places. When a property is missing, the error message just names User.
⚡ Use it on a parameter
Write:
function formatUser(user: User): string {
return user.name + " (" + user.age + ")";
}
console.log(formatUser(budi)); // Budi (17)
Meaning: The parameter user: User uses the interface's name, so the shape doesn't need to be written again. Inside the function, TypeScript knows user.name is a string, and a property that isn't in User is rejected. The interface disappears completely in the compiled JavaScript.
In the exercise, the result has to be exactly Budi (17), with one space before the opening parenthesis. Take name and age from the user parameter.
⚡ extends: an interface built on another
Write:
interface Admin extends User {
role: string;
}
const rina: Admin = { name: "Rina", role: "editor" };
Guess first: Admin is made from User with extends, then gets role. Is rina accepted? age isn't written in Admin.
Rejected: Property 'age' is missing. Properties inherited from User are still required, even when they aren't written again in Admin.
Meaning: extends User means Admin inherits (gets a copy of) every property of User, then adds role. An Admin can also be sent to a function whose parameter has the type User, because an Admin has every property a User needs.