Practice: TypeScript Basic Types

July 26, 2025

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

In the last article, we covered the fundamental building blocks of TypeScript: primitive types (string, number, boolean), collections like arrays and objects, and the helpful feature of type inference.

Now it's time to apply that knowledge. These exercises will help you get comfortable with adding type annotations, catching common errors, and understanding how TypeScript guides you toward writing more predictable code.


Question 1: Correcting Primitive Types (Easy)

The following code snippet is full of type errors. A developer has mixed up strings, numbers, and booleans.

let postTitle: string = 123;
let commentCount: number = "50 comments";
let isDraft: boolean = "true";

Your Task: Fix the variable assignments so that they match the declared TypeScript types. Then, add the correct type annotations to the variables in the second part of the code, relying on what you've learned.

// Part 2: Add type annotations
// In this part, you are given variables without any types.
// Your task is to add the correct type annotations based on the assigned values.
let authorName = "Alice";
let postViews = 2450;
let isFeatured = false;

<details> <summary>View Explanation</summary>

Let's break this down. The first part of the problem is about correcting mismatches. TypeScript is telling us that the values we're assigning don't fit the "box" we've defined for them.

Here’s the corrected code:

// The value must be a string
let postTitle: string = "My First Post";

// The value must be a number
let commentCount: number = 50;

// The value must be a boolean (true or false)
let isDraft: boolean = true;

The key idea here is that type annotations are a contract. When you say let postTitle: string, you're making a promise that this variable will always hold a string. TypeScript's job is to enforce that promise.

Now for the second part. We need to add the types ourselves.

let authorName: string = "Alice";
let postViews: number = 2450;
let isFeatured: boolean = false;

You might wonder, "But didn't the tutorial say TypeScript can infer these?" Yes, it absolutely can! If you wrote let authorName = "Alice";, TypeScript would correctly infer the type as string. However, this exercise is about getting comfortable with the syntax of explicitly writing out the types. Understanding the explicit form helps you understand what TypeScript is doing for you implicitly.

</details>


Question 2: Typing an Array of Objects (Easy-Medium)

You have a list of blog posts from an API. The code below tries to process them, but it's buggy because the types are not defined. A typo (titel instead of title) isn't being caught, and the code tries to use a string method on a number.

const posts = [
  { title: "TypeScript Basics", views: 1500, isPublished: true },
  { title: "React State Management", views: "2.5k", isPublished: false },
  { titel: "Advanced CSS", views: 800, isPublished: true },
];

posts.forEach((post) => {
  // This will cause a runtime error because of the typo 'titel'
  console.log(`Post: ${post.title.toUpperCase()}`);
  // This will also cause a runtime error for the second post
  console.log(`Views: ${post.views.toFixed(2)}`);
});

Your Task: Create a type annotation for the posts array. It should be an array of objects, where each object has a title (string), views (number), and isPublished (boolean). Fix the data in the array to match the types you've defined.

<details> <summary>View Explanation</summary>

The core of this problem is a very common scenario: working with data from an external source like an API. The data might not be perfectly consistent, and that's where TypeScript shines.

First, let's define the "shape" of a single post object. We need an object with three specific properties and their corresponding types.

const posts: { title: string; views: number; isPublished: boolean }[] = [
  // ...
];

Let's analyze this annotation:

  1. { title: string; views: number; isPublished: boolean }: This part defines the blueprint for a single post object.
  2. []: The square brackets at the end tell TypeScript that we're not dealing with a single object, but an array of these objects.

Now, as soon as we apply this type, TypeScript will immediately show us three errors in our data:

  1. { title: "React State Management", views: "2.5k", isPublished: false }
    • Error: Type 'string' is not assignable to type 'number'. TypeScript sees that "2.5k" is a string, not a number.
  2. { titel: "Advanced CSS", views: 800, isPublished: true }
    • Error: Property 'title' is missing... and Object literal may only specify known properties, and 'titel' does not exist.... TypeScript has caught our typo!

This is fantastic. We haven't even run the code, and we've already found all the bugs.

By defining the expected structure of our data upfront, we made our code more robust and caught errors that would have otherwise crashed our application at runtime.

</details>


Question 3: Typing a Function with Optional Data (Medium)

You're writing a function to create a user profile summary. The function should accept a user object, but sometimes the bio property might be missing. The current JavaScript code doesn't handle this, leading to a potential crash.

function createUserSummary(user) {
  const summary = `User: ${user.name}, Age: ${user.age}.`;
  // This line will crash if bio is missing
  const bioSummary = `Bio: ${user.bio.substring(0, 10)}...`;
  return summary + " " + bioSummary;
}

// Works fine
createUserSummary({
  name: "Bob",
  age: 35,
  bio: "A software developer from New York.",
});

// Crashes
createUserSummary({ name: "Charlie", age: 42 });

Your Task:

  1. Define the type for the user parameter. The bio property should be optional.
  2. Add a type annotation for the function's return value.
  3. Modify the function to safely handle cases where bio is not provided.

<details> <summary>View Explanation</summary>

This problem combines several concepts: function parameter types, object types with optional properties, and handling potentially missing values (undefined). It's a very realistic scenario.

Let's start by defining the type for the user object. We know name is a string and age is a number. The bio property is a string, but it might not exist. We can mark a property as optional by adding a ? before the colon.

function createUserSummary(user: {
  name: string;
  age: number;
  bio?: string;
}): string {
  // ... function body
}

Let's look at the annotations:

  • bio?: string: The ? makes the bio property optional. TypeScript now understands that user.bio could be a string or it could be undefined.
  • ): string: We've explicitly stated that this function will always return a string. TypeScript could infer this, but being explicit makes the function's contract clearer.

Now, if we try to use user.bio directly, TypeScript will stop us:

// const bioSummary = `Bio: ${user.bio.substring(0, 10)}...`;
// Error: 'user.bio' is possibly 'undefined'.

This is TypeScript's safety net in action. It's forcing us to account for the undefined case. The fix is to check if bio exists before we try to use it.

Here is the complete, safe solution:

function createUserSummary(user: {
  name: string;
  age: number;
  bio?: string;
}): string {
  let summary = `User: ${user.name}, Age: ${user.age}.`;

  // Check if the optional property exists
  if (user.bio) {
    // Inside this block, TypeScript knows user.bio is a string
    const bioSummary = ` Bio: ${user.bio.substring(0, 10)}...`;
    summary += bioSummary;
  }

  return summary;
}

// Works fine
console.log(
  createUserSummary({
    name: "Bob",
    age: 35,
    bio: "A software developer from New York.",
  })
);

// Also works fine now, no crash!
console.log(createUserSummary({ name: "Charlie", age: 42 }));

By making the bio property optional with ?, we told TypeScript about the uncertainty in our data. In return, TypeScript forced us to write safer code that handles both cases, preventing a common type of runtime error.

</details>

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee