0
0
Typescriptprogramming~10 mins

Type-safe API response handling in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a type for the API response.

Typescript
type ApiResponse = {
  data: string[];
  status: [1];
};
Drag options to blanks, or click blank then click option'
Aboolean
Bstring
Cnumber
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using string instead of number for status code.
Using any which loses type safety.
2fill in blank
medium

Complete the function signature to specify the return type as a Promise of ApiResponse.

Typescript
function fetchData(): [1] {
  return fetch('/api/data').then(res => res.json());
}
Drag options to blanks, or click blank then click option'
Aany
BApiResponse
Cvoid
DPromise<ApiResponse>
Attempts:
3 left
💡 Hint
Common Mistakes
Returning ApiResponse directly without Promise.
Using void which means no return value.
3fill in blank
hard

Fix the error in the type assertion to ensure the response is treated as ApiResponse.

Typescript
const response = await fetch('/api/data');
const data = (await response.json()) as [1];
Drag options to blanks, or click blank then click option'
AApiResponse
Bany
Cunknown
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using any which disables type checking.
Using string which does not match the object structure.
4fill in blank
hard

Fill both blanks to create a type guard function that checks if an object is ApiResponse.

Typescript
function isApiResponse(obj: any): obj is [1] {
  return obj && typeof obj.status === [2];
}
Drag options to blanks, or click blank then click option'
AApiResponse
Bstring
Cnumber
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Checking status as string instead of number.
Not using the correct type guard syntax.
5fill in blank
hard

Fill all three blanks to filter valid ApiResponse objects from an array.

Typescript
const responses: any[] = [...];
const validResponses = responses.filter((item): item is [1] => {
  return item && typeof item.status === [2] && Array.isArray(item.[3]);
});
Drag options to blanks, or click blank then click option'
AApiResponse
Bnumber
Cdata
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Checking wrong property names.
Using string instead of number for status type check.