Objects in TypeScript

Опубликовано: 01 Август 2026
на канале: Learn Language Hub
7
0

1) What is an Object in TypeScript?

Voiceover:
“In TypeScript, an object is a collection of key‑value pairs, where each key (property name) is a string or symbol, and each value can be any valid type. Objects are the foundation of most TypeScript structures.”

let user = { name: "Ores", age: 30 };


TypeScript infers the type as:

{ name: string; age: number }


So, you can’t later add or change properties to incompatible types:

user.age = "thirty"; // ❌ Error

🔹 2) Explicit Object Typing

You can describe the structure of an object explicitly:

let person: { name: string; age: number; isActive: boolean } = {
name: "Ada",
age: 25,
isActive: true
};


Why:
This makes the shape of your data clear and gives autocomplete and type‑safety in editors.

🔹 3) Optional and Readonly Properties
type Car = {
brand: string;
model?: string; // optional
readonly year: number; // cannot be changed
};

const car: Car = { brand: "Toyota", year: 2020 };
car.model = "Camry"; // ✅ OK
// car.year = 2022; // ❌ Error


Optional (?) properties can be omitted.
Readonly properties can’t be reassigned once set.

4) Index Signatures (Dynamic Keys)

“When you don’t know property names in advance, use an index signature.”

type Scores = {
[player: string]: number;
};

const game: Scores = {
Alice: 10,
Bob: 8,
};


Here, every property must have a number value, no matter the key name.

🔹 5) Using Record for Key‑Value Objects

A shorthand for index signatures:

type Scores = Record;

const points: Scores = {
Alice: 15,
Bob: 12,
};


Tip:
Record means “an object with known key types and known value types”.

🔹 6) Nested Objects

Objects can contain other typed objects:

type Address = {
city: string;
country: string;
};

type User = {
name: string;
address: Address;
};

const u: User = {
name: "Orest",
address: { city: "Lviv", country: "Ukraine" }
};


TypeScript checks both levels.

🔹 7) Object Type Inference

When you initialize an object, TypeScript infers its structure automatically.

const product = {
id: 1,
title: "Keyboard",
price: 99
};

// product.stock = 10; // ❌ Property 'stock' does not exist


If you need flexibility, define the shape with a type or interface that includes optional or index properties.

8) Objects and Interfaces

Objects are often typed using interfaces:

interface Employee {
id: number;
name: string;
active?: boolean;
}

const e1: Employee = { id: 101, name: "John" };


Interfaces and object type literals ({...}) are equivalent in most cases—interfaces are reusable and extendable.

🔹 9) object, Object, and {} — Know the Difference
Type Meaning Notes
object Any non‑primitive value (not string/number/boolean/null/undefined) Most useful for generic constraints
Object Base object type, includes all primitives Too broad, rarely used
{} “Any value except null/undefined” Very broad; avoid for strict typing

Example:

let a: object = { x: 1 }; // ✅
let b: Object = 123; // ✅ (too permissive)
let c: {} = "text"; // ✅ but not useful


Best practice: use object for “some object”, or define a shape { key: type } for specific data.

10) Narrowing Object Types
type Cat = { kind: "cat"; meow(): void };
type Dog = { kind: "dog"; bark(): void };
type Pet = Cat | Dog;

function makeSound(pet: Pet) {
if ("bark" in pet) pet.bark();
else pet.meow();
}


TypeScript narrows automatically inside conditionals.

🔹 11) Utility Types for Objects

TypeScript includes many built‑in helpers:

Utility Description
Partial Makes all props optional
Required Makes all props required
Readonly Prevents modification
Pick Selects specific keys
Omit Excludes specific keys
Record Builds a dictionary object
keyof T Extracts property names as a union

Example:

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


🔹 12) The satisfies Operator
const config = {
host: "localhost",
port: 3000,
} satisfies Record;


Voiceover:
“satisfies ensures the object matches a shape but keeps exact property types—it’s perfect for validating configs while preserving inference.”