0
0
Typescriptprogramming~15 mins

Union type syntax and behavior in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Union type syntax and behavior
📖 Scenario: Imagine you are building a simple form that accepts either a number or a string as input. You want to handle both types safely in your code.
🎯 Goal: Learn how to use union types in TypeScript to accept multiple types for a variable and handle them correctly.
📋 What You'll Learn
Create a variable with a union type of number | string
Assign values of both types to the variable
Use a type check to handle each type differently
Print the result based on the type
💡 Why This Matters
🌍 Real World
Union types help when you want to accept multiple kinds of input in forms, APIs, or functions safely.
💼 Career
Understanding union types is important for writing flexible and type-safe TypeScript code in web development jobs.
Progress0 / 4 steps
1
Create a variable with a union type
Create a variable called input with the union type number | string and assign it the number 42.
Typescript
Need a hint?

Use the pipe symbol | to combine types in TypeScript.

2
Assign a string value to the variable
Change the value of the variable input to the string "hello".
Typescript
Need a hint?

You can assign any value that matches the union type.

3
Use a type check to handle each type
Write an if statement that checks if input is a string. Inside the if, create a variable result and set it to input.toUpperCase(). Otherwise, set result to input + 1.
Typescript
Need a hint?

Use typeof to check the type before using type-specific methods.

4
Print the result
Write a console.log statement to print the value of result.
Typescript
Need a hint?

Use console.log(result); to show the output.