Published on

TypeScript Exercise - Solving Exercise 1

Authors
  • avatar
    Name
    hwahyeon
    Twitter

I heard about a TypeScript exercise today and thought it would be fun to solve one each day. Today, I solved Exercise 1.

Here's my solution:

export interface User {
  name: string
  age: number
  occupation: string
}

export const users: User[] = [
  {
    name: 'Max Mustermann',
    age: 25,
    occupation: 'Chimney sweep',
  },
  {
    name: 'Kate Müller',
    age: 23,
    occupation: 'Astronaut',
  },
]

export function logPerson(user: User) {
  console.log(` - ${user.name}, ${user.age}`)
}

console.log('Users:')
users.forEach(logPerson)

User[] defines an array of elements with the User type. Therefore, the correct type for users is User[]. In other words, users is an array that contains objects of the User type.

You can also define a type that is used exclusively for arrays. For example, the following approach is possible:

export type Users = {
  name: string
  age: number
  occupation: string
}[]

export const users: Users = [
  {
    name: 'Max Mustermann',
    age: 25,
    occupation: 'Chimney sweep',
  },
  {
    name: 'Kate Müller',
    age: 23,
    occupation: 'Astronaut',
  },
]

This method is suitable for declaring simple collections of data. However, as the project grows and the same User type is needed in contexts other than arrays, defining the User type separately as an interface becomes more advantageous. Doing so allows you to reuse the object type, making it more efficient in terms of scalability and maintainability.