Syncing account progress…

Back

Intermediate · 14 min

Interfaces as contracts

Use structural typing to pass compatible data through a small interface.

Require only what a function uses

An interface describes the properties a function needs. A value stored in a variable can have additional properties and still satisfy that contract. Compatibility depends on structure, not the name of its declared type.

interface Named { name: string }
function label(item: Named): string {
  return item.name;
}
const member = { name: "Mina", city: "Izmir" };
console.log(label(member));

Output

Mina

Check newly written objects

A fresh object literal is also checked for unexpected properties when assigned to an interface. This can catch a misspelled field. Optional fields still need a check or fallback when read; an interface does not create missing values.

interface Profile { name: string; city?: string }
const profile: Profile = { name: "Leo" };
console.log(profile.city ?? "Unknown");

Output

Unknown

Put it into practice

  1. Read the types and predict the output before running the examples.
  2. 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.

Satisfy the profile contract

Fix the type of the "name" property in "profile" by using the text "Mina". Keep the interface and display the profile name.

Show solution
interface Profile { name: string; score: number }
const profile: Profile = { name: "Mina", score: 3 };
const label = profile.name;
console.log(label);

The corrected object satisfies both required properties. Reading the name keeps a string type; no assertion or runtime conversion is needed.

Practice