Working with Union Types
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 32 of 73.
When you work with union types, TypeScript enforces an important safety rule: you can only access properties and methods that exist on all types in the union. This prevents runtime errors but means you need special techniques to access type-specific features.
Consider a function that accepts either a string or an array of strings. Both types have a length property, so you can safely access it:
function getLength(input: string | string[]): number {
return input.length; // Safe - both types have length
}However, if you try to use a method that only exists on one type, TypeScript will show an error. To safely access type-specific members, you need a type guard - a runtime check that narrows the type:
function processInput(input: string | string[]): void {
if (typeof input === "string") {
// TypeScript knows input is a string here
console.log(input.toUpperCase());
} else {
// TypeScript knows input is string[] here
console.log(input.join(", "));
}
}The typeof operator is one of the most common type guards. After the check, TypeScript automatically narrows the type within each branch, giving you full access to type-specific properties and methods while maintaining complete type safety.
Challenge
EasyCreate a function named processData that accepts a parameter called input of type string | string[] and returns a number. The function should use a type guard to determine the input type and behave as follows:
- If the input is a
string, return its length - If the input is a
string[], return the total number of characters across all strings in the array
Create another function named formatMessage that accepts a parameter called content of type number | boolean and returns a string. The function should use a type guard to determine the input type and behave as follows:
- If the input is a
number, return"Value: [number]" - If the input is a
boolean, return"Status: [boolean]"
The following inputs will be provided:
- First input: a string that represents either a single word or a JSON array of strings like
["apple", "banana", "cherry"] - Second input: a string that represents either a number or a boolean (
"true"or"false")
Process the inputs as follows:
- For the first input: if it starts with
"[", parse it as a JSON array of strings; otherwise, treat it as a single string - For the second input: if it's
"true"or"false", convert it to a boolean; otherwise, convert it to a number
Call processData with the processed first input and print the result. Then call formatMessage with the processed second input and print the result.
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 firstInput = inputs[0];
const secondInput = inputs[1];
// TODO: Write your code here
// Create the processData function with type guard
// Create the formatMessage function with type guard
// Process the inputs according to the requirements
// Call the functions and print the resultsThis 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