Published on

TypeScript Exercise - Solving Exercise 2

Authors
  • avatar
    Name
    hwahyeon
    Twitter

Today, I solved Exercise 2.

The key point of Exercise 2 seemed to be about using |. The | operator is used to define a type that allows selecting one among multiple types.

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

interface Admin {
  name: string
  age: number
  role: string
}

export type Person = User | Admin

export const persons: Person[] = [
  {
    name: 'Max Mustermann',
    age: 25,
    occupation: 'Chimney sweep',
  },
  {
    name: 'Jane Doe',
    age: 32,
    role: 'Administrator',
  },
  {
    name: 'Kate Müller',
    age: 23,
    occupation: 'Astronaut',
  },
  {
    name: 'Bruce Willis',
    age: 64,
    role: 'World saver',
  },
]

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

persons.forEach(logPerson)

Both User and Admin share the name and age fields. To reduce duplication, these fields can be extracted into a common interface, resulting in the following structure:

interface PersonBase {
  name: string
  age: number
}

interface User extends PersonBase {
  occupation: string
}

interface Admin extends PersonBase {
  role: string
}

export type Person = User | Admin

Even though I've only solved Exercises 1 and 2 so far, Exercise 2 felt like a deeper exploration of Exercise 1. It seems that future exercises will also progressively build on previous ones. To avoid overlapping with potential topics in upcoming exercises, I'll keep this write-up concise and stop here for now.