Extracting Numbers, Booleans, and Strings from a Mixed TypeScript Array
TypeScript Advance Types: Exercise-6 with Solution
Write a TypeScript program that declares an array containing both numbers and strings. Use type assertions to extract number, string and boolean values from the array.
Sample Solution:
TypeScript Code:
// Declare an array 'mixedData' with numbers and strings
const mixedData: (number | string | boolean)[] = [-12, "one", 10, false, "two", 34, true, "three"];
console.log("Original array elements:", mixedData);
// Use type assertion to extract only numbers
const numbersOnly: number[] = mixedData.filter((item): item is number => typeof item === "number");
// Print the extracted numbers
console.log("Numbers Only:", numbersOnly);
// Use type assertion to extract only booleans
const booleanOnly: boolean[] = mixedData.filter((item): item is boolean => typeof item === "boolean");
// Print the extracted numbers
console.log("Boolean Only:", booleanOnly);
// Use type assertion to extract only booleans
const stringOnly: string[] = mixedData.filter((item): item is string => typeof item === "string");
// Print the extracted numbers
console.log("String Only:", stringOnly);
Explanations:
In the exercise above -
- First, we declare an array 'mixedData' with elements of type number | string | boolean. This means it can contain both numbers and strings.
- Next we use the "filter()" method to extract only numbers from the 'mixedData' array. We use a type assertion in the filter's callback function to tell TypeScript that we expect the filtered elements to be of type 'number', 'string' and 'boolean' separately.
- Finally we print the extracted numbers to the console.
Output:
"Original array elements:" [-12, "one", 10, false, "two", 34, true, "three"] "Numbers Only:" [-12, 10, 34] "Boolean Only:" [false, true] "String Only:" ["one", "two", "three"]
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: Check if a number is odd.
Next: Type assertion in TypeScript.
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