CodeBlanks Logo Icon CodeBlanks

Summary - Type assertion

Write a program that safely parses an API response with assertion.

Summary - Type assertion

In this group you learned type assertion methods. The as keyword and <type> angle bracket assert types at compile time; neither changes the value at runtime. unknown values are first narrowed with typeof. For real conversion, functions like Number() are used.

const response: unknown = "5";
if (typeof response === "string") {
  const n = Number(response);
  console.log(n + 1);
}

Practice Parse API response

The yanit variable is of type unknown with value "42". First check if it is string with typeof. If so, do real conversion with Number(), add 1, and print the result with console.log.

Starter code

index.ts
// yanit degiskeninin string olup olmadigini typeof ile kontrol et
// eger stringse Number ile donustur, 1 ekle ve yazdir

const yanit: unknown = "42";

Sample solution

index.ts
const yanit: unknown = "42";
if (typeof yanit === "string") {
  const n = Number(yanit);
  console.log(n + 1);
}

Expected output

43

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the best order to safely process an API response received as unknown?

  • Receive as unknown, force cast with as
  • Receive as unknown, call methods directly
  • Receive as any, do no checks
  • Receive as unknown, narrow with typeof, then use Correct answer

Explanation: The safest way: receive as unknown, narrow with typeof, then use. Direct use or forced casting is error-prone.

2 Narrow unknown with string

Question
const yanit: unknown = "basarili";
if (typeof yanit === "____") {
  console.log(yanit.length);
}
Answer
const yanit: unknown = "basarili";
if (typeof yanit === "string") {
  console.log(yanit.length);
}

Explanation: To narrow an unknown string value, compare with "string" using typeof.

3 Type assertion summary

Term Meaning
as Universal assertion
<> Angle bracket syntax
unknown Safe any alternative
typeof Narrowing operator

All lessons in Intermediate