Interfaces and objects in TypeScript
Describe the shape of an object and use it in a function. Press Run to try it, then change the code and run it again.
interface Product {
name: string;
price: number;
inStock?: boolean;
}
const cart: Product[] = [
{ name: 'Keyboard', price: 1499, inStock: true },
{ name: 'Mouse', price: 599 },
];
const total = cart.reduce((sum, p) => sum + p.price, 0);
console.log(`Total: ₹${total}`);
console.table(cart);
Output
Press Run to see the output.
More TypeScript examples
- Hello, World · Print a line of text with a typed variable.
- Generics · Write one function that works with any type, safely.
- Union types and narrowing · Handle values that can be one of several types.
- Catch a type error · See how TypeScript stops a bug before the code runs.
- Async and await · Wait for promises with typed results.