iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Objects

Object types describe shapes — what keys exist and what their values are typed as. The bread and butter of TypeScript.

Inline object types

TS
const user: { id: number; name: string; active: boolean } = {
    id: 1,
    name: 'Ada',
    active: true,
};

Optional properties

TS
const u: { id: number; name: string; email?: string } = {
    id: 1,
    name: 'Ada',
};
u.email = 'ada@example.com';      // OK

Readonly properties

TS
const u: { readonly id: number; name: string } = { id: 1, name: 'Ada' };
u.name = 'Linus';      // OK
// u.id = 2;           // ✗ error

Index signatures — open shapes

TS
const counters: { [key: string]: number } = {};
counters.hits   = 1;
counters.misses = 0;

// Or with Record:
const counters2: Record<string, number> = {};

Named shapes — type aliases & interfaces

TS
type User = {
    id: number;
    name: string;
};

// or

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

const u: User = { id: 1, name: 'Ada' };

Excess property checks

Object literals get an extra strict check that catches typos:

TS
type User = { id: number; name: string };

// ✗ error — "emial" not in User
const u: User = { id: 1, name: 'Ada', emial: 'ada@example.com' };
Tip: When TS warns about an extra property, don't paper over it with as User — that's silencing a real bug. Either fix the typo, widen the type, or split into a different type.

Example

Example
const user: { id: number; name: string; email?: string } = {
  id: 1,
  name: 'Ada',
};
user.email = 'ada@example.com';
console.log(user);
Try it Yourself »

Exercise

Optional property marker.

{ id: number; email : string }

Test yourself

Q1. An optional property is marked with…
Q2. TS's "excess property check" runs on…
Q3. Open-shape dictionaries are written as…

Discussion

Loading…