TS PlaygroundLearnJavaScriptTypes & Interfaces
javascript/beginner

Types & Interfaces

Define custom types and interfaces to describe the shape of your data.


Types and Interfaces

TypeScript lets you describe the shape of objects with type aliases and interface declarations.

type alias

type User = {
  name: string;
  age: number;
};

interface

interface Product {
  id: number;
  name: string;
  price: number;
}

Both are nearly identical. type is slightly more flexible (union types, tuples), interface is preferred for object shapes by many teams.

Using your types

function formatUser(user: User): string {
  return `${user.name} (${user.age})`;
}

Your task

Define and export a type named Point with:

  • x: number
  • y: number

Then export a function named distance that takes two Point values and returns the Euclidean distance between them as a number.

export type Point = { ... };

export function distance(a: Point, b: Point): number {
  // hint: Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2)
}
// Define and export a type named 'Point' with x and y number fields
// Then export a 'distance' function that returns the distance between two Points

Click Run Tests to see results
FunctionsInterfaces & Object Types