Skip to content
AgileLogics
5 min read

Interfaces

Prerequisites: Objects and type shapes

An interface gives a reusable name to an object shape, instead of repeating the same inline type everywhere it's needed.

Syntax

interface Name {
    property: Type;
}

Example

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

function greet(user: User): string {
    return `Hello, ${user.name}!`;
}

greet({ name: "Ada", age: 25 });

Expected output

Hello, Ada!

A property followed by ? is optional: age?: number means an object can omit age entirely and still match the interface.

Practice

Write an interface Product with name: string and price: number, and a function describe(product: Product) that returns `${name} costs $${price}`.

Show solution
interface Product {
    name: string;
    price: number;
}

function describe(product: Product): string {
    return `${product.name} costs $${product.price}`;
}