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?
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}`);
}Look at how the isSuccess function narrows the type of response.
The isSuccess function is a type guard that checks if response.status is 'success'. If true, TypeScript knows response has a data property with user info. So, response.data.name is 'Alice'.
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?
Think about a way to safely check if a property exists before accessing it.
The optional chaining operator ?. allows you to safely access nested properties. If any part is null or undefined, it returns undefined instead of throwing an error.
Examine the following code snippet. What error will TypeScript report?
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());
}
}Check if response.data is always defined when status is 'ok'.
The data property is optional. Even if status is 'ok', data might be undefined. Accessing response.data.value without checking causes a possible undefined error.
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?
type ApiResponse = { status: 'success'; data: { id: number; name: string } } | { status: 'error'; message: string };
const json = '{"status":"success","data":{"id":10,"name":"Bob"}}';Parsing JSON returns any. How do you check the shape before using it?
Option A parses JSON and then checks properties manually before using them. This avoids unsafe assumptions. Options A and B trust the JSON blindly, which is unsafe. Option A accesses nested data without checks, risking runtime errors.
Given this TypeScript code that handles a discriminated union API response, what will be printed?
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);Check how the switch uses the discriminated union type property.
The render function uses response.type to narrow the union. For type === 'image', it accesses url and alt safely. So the output is the formatted string with those values.