Complete the code to check if the variable is a string.
function checkType(value: unknown) {
if (typeof value === [1]) {
return true;
}
return false;
}The typeof operator returns a string indicating the type. To check if value is a string, compare it to "string".
Complete the code to narrow the type using a type guard.
function process(value: string | number) {
if (typeof value === [1]) {
return value.toUpperCase();
}
return value.toFixed(2);
}To call toUpperCase(), value must be a string. So check if typeof value === "string".
Fix the error by completing the code to correctly narrow the type.
function example(value: string | null) {
if (value [1] null) {
return value.length;
}
return 0;
}To safely access value.length, ensure value is not null. Use !== null to check this.
Fill both blanks to create a type guard that checks for an array of numbers.
function isNumberArray(value: unknown): value is number[] {
return Array.isArray(value) && value.every(item => typeof item [1] [2]);
}Use === to strictly compare typeof item with "number" to confirm all items are numbers.
Fill all three blanks to create a function that narrows a union type using control flow.
function formatValue(value: string | number | boolean) {
switch (typeof value) {
case [1]:
return value.toUpperCase();
case [2]:
return value.toFixed(1);
case [3]:
return value ? "Yes" : "No";
}
}The typeof operator returns "string", "number", or "boolean" for these types. Use these in the switch cases to narrow the type and call appropriate methods.