O

Objects

Objects can be typed using interfaces or type aliases, providing structure and type safety.

Code

typescript
1// Object type annotation inline
2let user: { name: string; age: number } = {
3 name: "Alice",
4 age: 30,
5};
6
7// Using an interface
8interface Person {
9 name: string;
10 age: number;
11 email?: string; // Optional property
12}
13
14const alice: Person = {
15 name: "Alice",
16 age: 30,
17 email: "alice@example.com",
18};
19
20const bob: Person = {
21 name: "Bob",
22 age: 25,
23 // email is optional, so we can omit it
24};
25
26// Readonly properties
27interface Config {
28 readonly apiKey: string;
29 readonly endpoint: string;
30}
31
32const config: Config = {
33 apiKey: "secret-key-123",
34 endpoint: "https://api.example.com",
35};
36
37// config.apiKey = "new-key"; // Error: Cannot assign to 'apiKey'
38
39// Nested objects
40interface Company {
41 name: string;
42 address: {
43 street: string;
44 city: string;
45 country: string;
46 };
47}
48
49const company: Company = {
50 name: "Tech Corp",
51 address: {
52 street: "123 Main St",
53 city: "San Francisco",
54 country: "USA",
55 },
56};
57
58console.log(`${alice.name} is ${alice.age} years old`);
59console.log(`Company: ${company.name}, ${company.address.city}`);

Run this example locally

$ npx ts-node basics/objects.ts