w3resource

TypeScript type guard function

TypeScript Advance Types: Exercise-4 with Solution

Write a TypeScript function that takes an argument of type string | number. Inside the function, use a type guard to check whether the argument is a string or a number. Then, log the appropriate message accordingly.

Sample Solution:

TypeScript Code:

// Function 'printElement' that accepts an argument of type 'string | number'
function printElement(element: string | number): void {
  // Type guard to check if 'element' is a string
  if (typeof element === "string") {
    console.log("Element is a string:", element);
  }
  // Type guard to check if 'element' is a number
  else if (typeof element === "number") {
    console.log("Element is a number:", element);
  }
  // Default case
  else {
    console.log("Element is neither a string nor a number.");
  }
}

// Test the 'printElement' function
printElement("TypeScript"); // Output: Element is a string: TypeScript
printElement(200);      // Output: Element is a number: 200
printElement(false);    // Output: Element is neither a string nor a number.

Explanations:

In the exercise above -

  • First, we define a function "printElement()" that takes an argument 'element' of type string | number.
  • Inside the function, we use type guards (typeof element === "string" and typeof element === "number") to check the type of the 'element' argument.
  • If 'element' is a string, it logs the message "Element is a string" along with the actual string value.
  • If 'element' is a number, it logs the message "Element is a number" along with the actual number value.
  • If the 'element' is neither a string nor a number (default case), it logs the message "Element is neither a string nor a number."
  • Finally, we tested the "printElement()" function with different values, including a string, a number, and a boolean, to demonstrate how it handles different types.

Output:

"Element is a string:"
"TypeScript"
"Element is a number:"
200
"Element is neither a string nor a number."

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript interface, type, and union types.
Next: Check if a number is odd.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/typescript-exercises/typescript-advance-types-exercise-4.php