Lesson 7 of 15
Union Types
Union Types
Building on Optional Properties: In the previous lesson, you saw that an optional property like
age?: numberactually has the typenumber | undefined— that|is a union! You have already been using union types without realizing it. Now let's explore them fully.
A union type means a value can be one of several types, written with |:
let input: string | number;
input = "hello"; // OK
input = 42; // OK
input = true; // Error: 'boolean' not in the union
Unions in Functions
function stringify(val: string | number | boolean): string {
return String(val);
}
console.log(stringify("hello")); // hello
console.log(stringify(42)); // 42
console.log(stringify(true)); // true
Unions with null and undefined
A common union is T | null for values that might be absent:
function find(id: number): string | null {
if (id === 1) return "Alice";
return null;
}
const name = find(1); // string | null
const missing = find(2); // string | null
Your Task
Write function describe(val: string | number): string that returns:
"string of length N"ifvalis a string (where N is the length)"number: N"ifvalis a number
TypeScript loading...
Loading...
Click "Run" to execute your code.