Complete the code to check if the variable is a string.
function checkType(x: string | number) {
if (typeof x === [1]) {
return x.toUpperCase();
}
return x;
}The typeof operator returns a string indicating the type. To check if x is a string, compare it to "string".
Complete the code to narrow the type using equality check.
function process(value: string | null) {
if (value [1] null) {
return value.toLowerCase();
}
return "No value";
}Use !== for strict inequality to check if value is not null. This narrows the type to string, allowing safe use of toLowerCase().
Fix the error in the equality narrowing condition.
function example(input: string | number) {
if (typeof input [1] "string") {
return input.toLowerCase();
}
return input;
}Use the strict equality operator === with typeof input to check if input is a string. This narrows the type to string.
Fill both blanks to correctly narrow the type and use the value.
function handle(input: string | number) {
if (typeof input [1] [2]) {
return input.toUpperCase();
}
return input.toFixed(2);
}To check if input is a string, use typeof input === "string". This narrows the type so you can safely call string methods like toUpperCase().
Fill all three blanks to correctly narrow types and handle both cases.
function format(value: string | number | null) {
if (value [1] null) {
if (typeof value [2] [3]) {
return value.toUpperCase();
}
return value.toFixed(1);
}
return "No value";
}First, check that value is not null using !== null. Then check if value is a string with typeof value === "string". This lets you safely call toUpperCase(). Otherwise, assume it's a number and call toFixed(1).