Using union types in TypeScript functions

TypeScript Advance Types: Exercise-2 with Solution

Write a TypeScript program that creates a function combine that accepts two parameters of types boolean and number. It returns a value that can be either a boolean or a number. Use a union type to achieve this.

Sample Solution:

TypeScript Code:

// Function 'combine' that accepts boolean and number parameters
function combine(param1: boolean, param2: number): boolean | number {
  if (param1) {
    return param2 * 3; // Return a number if param1 is true
  } else {
    return !param1; // Return a boolean if param1 is false

// Test the 'combine' function
const result1: boolean | number = combine(true, 24);
const result2: boolean | number = combine(false, -20);

console.log("Result-1:", result1);  
console.log("Result-2:", result2);


In the exercise above -

  • First, we define a function "combine()" that takes two parameters, 'param1' of type boolean and 'param2' of type number.
  • Inside the function, we use a conditional statement (if) to check the value of 'param1'. If 'param1' is true, we return a number (param2 * 2), and if param1 is false, we return a boolean (!param1).
  • Next we test the "combine()" function by calling it with different values and assigning the results to variables 'result1' and 'result2'.
  • Finally we use console.log to print the results to the console, demonstrating that the function can return values of either type 'boolean' or type 'number' based on the input parameters.



TypeScript Editor:

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

Previous: Union and intersection types in TypeScript.
Next: TypeScript interface, type, and union types.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.