age with a number value.isAdult that will hold a boolean value.if statement to set isAdult to true if age is 18 or more, otherwise false."User is an adult" if isAdult is true, otherwise print "User is not an adult".age with a number value.isAdult that will hold a boolean value.if statement to set isAdult to true if age is 18 or more, otherwise false."User is an adult" if isAdult is true, otherwise print "User is not an adult".age variableage and set it to the number 20.Use let age: number = 20; to create the variable.
isAdult variableisAdult and set it to false.Use let isAdult: boolean = false; to create the variable.
if statement to update isAdultif statement with the condition age >= 18 to set isAdult to true inside the block.Write if (age >= 18) { isAdult = true; } to update the variable.
isAdultif statement to print "User is an adult" if isAdult is true, otherwise print "User is not an adult".Use if (isAdult) { console.log("User is an adult"); } else { console.log("User is not an adult"); }.
What does TypeScript's control flow analysis primarily help with?
Which of the following TypeScript code snippets correctly narrows a variable's type using control flow analysis?
let value: string | number = 5;
if (typeof value === 'string') {
console.log(value.toUpperCase());
}typeof value === 'string' narrows value to string inside the if block.value is string here, calling toUpperCase() is safe and valid.toUpperCase() inside the if block -> Option DWhat will be the output of this TypeScript code?
function checkValue(x: string | number) {
if (typeof x === 'number') {
return x.toFixed(2);
} else {
return x.toUpperCase();
}
}
console.log(checkValue('hello'));
console.log(checkValue(3.14159));'hello', the else block runs, returning 'HELLO' after toUpperCase().3.14159, the if block runs, returning '3.14' after toFixed(2).Identify the error in this TypeScript code related to control flow analysis:
function process(input: string | null) {
if (input) {
console.log(input.toLowerCase());
} else {
console.log(input.toLowerCase());
}
}input is null, so calling toLowerCase() causes a runtime error.input in the if block but not in else, so unsafe call happens.toLowerCase() on null in the else block causes a runtime error -> Option AGiven this TypeScript code, what is the best way to fix the control flow analysis issue to avoid errors?
function formatInput(input: string | number | null) {
if (typeof input === 'string') {
return input.trim();
} else if (typeof input === 'number') {
return input.toFixed(1);
}
return input.trim();
}return input.trim() runs when input is null, causing an error.if (input !== null) before calling trim() prevents errors.return to avoid calling trim() on null -> Option APass the test and this pattern moves unknown