0
0
Typescriptprogramming~20 mins

Type-safe API response handling in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type-safe API Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this TypeScript code with type guards?

Consider this TypeScript code that fetches user data and uses a type guard to check the response type. What will be logged to the console?

Typescript
type User = { id: number; name: string };

type ApiResponse = { status: 'success'; data: User } | { status: 'error'; message: string };

function isSuccess(response: ApiResponse): response is { status: 'success'; data: User } {
  return response.status === 'success';
}

const response: ApiResponse = { status: 'success', data: { id: 1, name: 'Alice' } };

if (isSuccess(response)) {
  console.log(`User name: ${response.data.name}`);
} else {
  console.log(`Error: ${response.message}`);
}
AError: undefined
BTypeError at runtime
CUser name: Alice
DUser name: undefined
Attempts:
2 left
💡 Hint

Look at how the isSuccess function narrows the type of response.

🧠 Conceptual
intermediate
1:30remaining
Which TypeScript feature ensures safe access to nested API response data?

You receive a nested API response object that may or may not have certain properties. Which TypeScript feature helps you safely access these nested properties without runtime errors?

AType casting with angle brackets (<>)
BNon-null assertion operator (!)
CType assertion (as keyword)
DOptional chaining operator (?.)
Attempts:
2 left
💡 Hint

Think about a way to safely check if a property exists before accessing it.

🔧 Debug
advanced
2:00remaining
What error does this TypeScript code produce when handling API response?

Examine the following code snippet. What error will TypeScript report?

Typescript
interface ApiResponse {
  status: 'ok' | 'fail';
  data?: { id: number; value: string };
  error?: string;
}

function handleResponse(response: ApiResponse) {
  if (response.status === 'ok') {
    console.log(response.data.value.toUpperCase());
  } else {
    console.error(response.error.toUpperCase());
  }
}
AType 'string' is not assignable to type 'number' error
BObject is possibly 'undefined' error on 'response.data.value'
CNo error, code compiles fine
DProperty 'toUpperCase' does not exist on type 'number'
Attempts:
2 left
💡 Hint

Check if response.data is always defined when status is 'ok'.

🚀 Application
advanced
2:30remaining
Which code snippet correctly parses and type-checks a JSON API response?

You receive a JSON string from an API. You want to parse it and ensure it matches the ApiResponse type safely. Which snippet correctly does this with type safety?

Typescript
type ApiResponse = { status: 'success'; data: { id: number; name: string } } | { status: 'error'; message: string };

const json = '{"status":"success","data":{"id":10,"name":"Bob"}}';
A
const response = JSON.parse(json);
if (response.status === 'success' &amp;&amp; typeof response.data?.id === 'number') {
  // safe to use response.data
}
Bconst response = JSON.parse(json) as ApiResponse;
Cconst response: ApiResponse = JSON.parse(json);
D
const response = JSON.parse(json);
console.log(response.data.name);
Attempts:
2 left
💡 Hint

Parsing JSON returns any. How do you check the shape before using it?

Predict Output
expert
2:00remaining
What is the output of this TypeScript discriminated union handling code?

Given this TypeScript code that handles a discriminated union API response, what will be printed?

Typescript
type ApiResponse =
  | { type: 'text'; content: string }
  | { type: 'image'; url: string; alt: string };

function render(response: ApiResponse) {
  switch (response.type) {
    case 'text':
      return `Text: ${response.content}`;
    case 'image':
      return `Image: ${response.url} (alt: ${response.alt})`;
  }
}

const result = render({ type: 'image', url: 'http://img.com/pic.jpg', alt: 'A picture' });
console.log(result);
AImage: http://img.com/pic.jpg (alt: A picture)
BText: undefined
CImage: undefined (alt: undefined)
DRuntime error: Property 'content' does not exist
Attempts:
2 left
💡 Hint

Check how the switch uses the discriminated union type property.