Union Types ('|')
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 31 of 73.
Sometimes you need a variable that can hold different types of values depending on the situation. For example, a user ID might be stored as either a string like "user123" or a number like 42. TypeScript's union types solve this problem by allowing a variable to be one of several specified types.
Union types use the pipe character (|) to combine multiple types. The syntax reads naturally as "this OR that":
let userId: string | number;
userId = "user123"; // Valid - string
userId = 42; // Valid - number
userId = true; // Error - boolean not allowedYou can combine any types in a union, not just primitives. This flexibility makes union types particularly useful for function parameters that need to accept multiple input formats:
function displayMessage(content: string | number): void {
console.log("Message: " + content);
}
displayMessage("Hello!"); // Works with string
displayMessage(404); // Works with numberUnion types provide type safety while maintaining flexibility - TypeScript ensures you only use values that match one of the specified types, preventing runtime errors from unexpected data types.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a function named printId that accepts a parameter called id of type string | number and prints it to the console. The function should have an explicit return type of void.
Create another function named processValue that accepts a parameter called data of type boolean | string and returns it unchanged. The function should have an explicit return type of boolean | string.
Create a third function named formatOutput that accepts a parameter called input of type number | string and returns a formatted string. If the input is a number, return "Number: [input]". If the input is a string, return "Text: [input]". The function should have an explicit return type of string.
The following inputs will be provided:
- First input: a value that can be either a string or number (for
printId) - Second input: a value that can be either a boolean or string (for
processValue) - Third input: a value that can be either a number or string (for
formatOutput)
Read the three inputs, call each function with the appropriate input, and handle the outputs as follows:
- Call
printIdwith the first input (this will print directly) - Call
processValuewith the second input and print the returned value - Call
formatOutputwith the third input and print the returned value
Note: The first input will be provided as a string, but if it represents a number (like "123"), convert it to a number before passing it to printId. The second input will be provided as a string, but if it's "true" or "false", convert it to the corresponding boolean value. The third input will be provided as a string, but if it represents a number, convert it to a number.
Cheat sheet
Union types allow a variable to be one of several specified types using the pipe character (|):
let userId: string | number;
userId = "user123"; // Valid - string
userId = 42; // Valid - number
userId = true; // Error - boolean not allowedUnion types work with function parameters to accept multiple input formats:
function displayMessage(content: string | number): void {
console.log("Message: " + content);
}
displayMessage("Hello!"); // Works with string
displayMessage(404); // Works with numberUnion types provide type safety while maintaining flexibility, ensuring you only use values that match one of the specified types.
Try it yourself
import * as fs from "fs";
// Read inputs
const stdinBuffer: Buffer = fs.readFileSync(0);
const inputs: string[] = stdinBuffer.toString().trim().split('\n');
const input1 = inputs[0];
const input2 = inputs[1];
const input3 = inputs[2];
// Convert inputs to appropriate types
const firstInput = isNaN(Number(input1)) ? input1 : Number(input1);
const secondInput = input2 === "true" ? true : input2 === "false" ? false : input2;
const thirdInput = isNaN(Number(input3)) ? input3 : Number(input3);
// TODO: Write your code here
// Create the three functions: printId, processValue, and formatOutput
// TODO: Call the functions with the appropriate inputs and handle outputsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples