Start learning free

LESSON 189 OF 675 · TYPESCRIPT ESSENTIALS

Interfaces in TypeScript

Lesson

TL ; DR:

An interface gives a name to the shape of an object: which properties it must have, and what type each one is.

interface User {
    name: string;
    age: number;
}

From then on, User works anywhere a type works — in variable annotations, in function parameters, everywhere.



Full lesson:

So far, your type annotations described single values: let age: number = 31;. But real programs pass whole objects around — a user, a product, a point on a map. An interface describes such an object once, so the compiler can check every place it is used.


Using an interface:

You attach an interface to an object with the usual colon annotation, and you can use it as a function parameter type too:

interface User {
    name: string;
    age: number;
}

function greet(user: User): void {
    console.log("Hello, " + user.name + "!");
}

const alice: User = { name: "Alice", age: 30 };
greet(alice);

The output of this code is:

Hello, Alice!

Inside greet, the compiler knows user has a name and an age — autocomplete works, typos are caught, and nothing is ever mysteriously undefined.

Note that an interface exists only at compile time. It produces no JavaScript at all — it is purely a contract the compiler enforces while you write the code.


The trap — the shape must match exactly:

An object annotated with an interface must have every declared property. Leave one out:

const bob: User = { name: "Bob" };

and the compiler refuses:

error TS2741: Property 'age' is missing in type '{ name: string; }' but required in type 'User'.

And when you assign an object literal directly, TypeScript also runs an excess property check — properties the interface does not mention are rejected too:

const eve: User = { name: "Eve", age: 22, city: "Paris" };
error TS2353: Object literal may only specify known properties, and 'city' does not exist in type 'User'.

Read these two messages carefully — they name the missing or extra property and the interface it clashes with. Fixing them is exactly how interface bugs get solved in real projects.


Assignment
Follow the Coding Tutorial and let's put an interface to work:

  • Declare an interface User with name: string and age: number.
  • Define a function describe(user: User): void that prints "name = " + user.name and, on the next line, "age = " + user.age.
  • Create a constant ada of type User with name "Ada" and age 36.
  • Call describe(ada).

The expected output is:

name = Ada
age = 36

Hint
Look at the examples above if you get stuck.


STEP 1 OF 8
    Ctrl + Enter to check