Complete the code to declare a variable that cannot be null or undefined.
let name: string = [1];With strict null checks, a variable of type string cannot be assigned null or undefined. Assigning a string literal like "Alice" is correct.
Complete the code to allow the variable to hold either a string or null.
let username: string[1] = null;Using | null creates a union type allowing username to be a string or null.
Fix the error by completing the code to safely access the length of a possibly null string.
function getLength(str: string | null): number | undefined {
return str[1].length;
}The optional chaining operator ?. safely accesses length only if str is not null.
Fill both blanks to check if a variable is not null before accessing its property.
if (user [1] null [2] user.name) { console.log(user.name); }
We check that user is not null with !== and then use && to ensure user.name exists before logging.
Fill all three blanks to create a function that returns the length of a string or zero if null or undefined.
function safeLength(str: string[1]): number { return str?.length[2][3]; }
The parameter type allows string, null, or undefined. The nullish coalescing operator ?? returns 0 if str is null or undefined.