Union and intersection types in TypeScript
TypeScript Advance Types: Exercise-1 with Solution
Write a TypeScript program that declares a variable 'result' that can hold either a 'string' or a 'number'. Now write a function that takes an argument of type 'string | number | boolean' and logs its type.
Sample Solution:
TypeScript Code:
// Declare a variable 'result' with a broader union type
let result: string | number | boolean;
// Function that logs the type of the argument
function logType(arg: string | number | boolean): void {
if (typeof arg === "string") {
console.log("Type: string");
} else if (typeof arg === "number") {
console.log("Type: number");
} else if (typeof arg === "boolean") {
console.log("Type: boolean");
} else {
console.log("Type: unknown");
}
}
// Testing the function with different argument types
result = "TypeScript ";
logType(result); // Output: Type: string
result = 100;
logType(result); // Output: Type: number
result = true; // Assigning a boolean value
logType(result); // Output: Type: boolean
Explanations:
In the exercise above -
- First, we declare a variable 'result' with the union type string | number | boolean, which means it can hold values of either 'string' or 'number' or 'boolean' types.
- Define a function "logType()" that takes an argument 'arg' of type string | number | boolean. Inside the function, we use the 'typeof' operator to check the type of arg and log the corresponding type.
- Finally, we test the "logType()" function by assigning 'result' different values, such as a string and a number, and then calling the function to log their types.
Output:
"Type: string" "Type: number" "Type: boolean"
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript Advance Types Exercises Home
Next: Using union types in TypeScript functions.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics