How to properly declare an array of objects in TypeScript: a complete guide for beginners
Hello everyone! I just started learning TypeScript and encountered a problem when declaring an array of objects. I'm trying to write a simple functionality for a user list, but TypeScript keeps throwing errors.\n\nHere's my code:\n\n```typescript\nconst users = [\n { name: "Ivan", age: 25 },\n { name: "Maria", age: 30 },\n { name: "Peter", age: 28 }\n];\n\nfunction getUserNames(users: ???) {\n return users.map(user => user.name);\n}\n```\n\nI tried different options: `users: Array`, `users: any[]`, but either TypeScript complains or autocomplete is lost in the editor. For example, when I write `users: any[]`, when accessing `user.name` the editor doesn't suggest object properties, and I might accidentally type a non-existent field.\n\nAnother problem: sometimes I want the array to contain objects with
No answers yet.
Log in to leave an answer
Blogs
How to Add 1 Day to NSDate: 5 Fatal Mistakes for Beginners in Swift
Tests in Go Subdirectories: Complete Guide for Beginners
GetHashCode and Equals: Why Overriding Them Is Critical for C#
Record in TypeScript: what it is and how to use it for beginners