Skip to content

Typescript Exercises 1

Posted on:February 20, 2023 at 03:06 AM

Typescript Exercise 1


Exercise 1


Given the data, define the interface User and use it accordingly.


export type User = unknown;

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

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

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

How I Solved This Problem

Since Type User is Unknown, in compile time Javascript Engine doesn’t know what type the users variable is.

We know users is an Array of Objects and as we can see type Users is missing properties of name, age and occupation

type User should have below properties with types

type User = {
  name: string;
  age: number;
  occupation: string;
};

We can fix this facing type errors by assigning properties to type User

export type 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);