w3resource

TypeScript conditional type example

TypeScript Advance Types: Exercise-13 with Solution

Write a TypeScript program that creates a conditional type. The program takes an array and a type as parameters and returns an array containing only elements of the specified type. Test the conditional type with an array of mixed types and extract only numbers or strings, depending on the input type parameter.

Sample Solution:

TypeScript Code:

// Define a conditional type 'FilterArrayByType' that takes an array type 'T[]' and a type 'U'
type FilterArrayByType = T extends (infer Item)[]
  ? Item extends U
    ? Item[]
    : never
  : never;

// Test the 'FilterArrayByType' conditional type with an array of mixed types
const mixedArray: (string | number | boolean)[] = ["Red", 100, "Green", true, 344, "White"];

// Extract only numbers from the mixed array using the conditional type
const numbersArray: number[] = mixedArray.filter((item) => typeof item === 'number');

// Extract only strings from the mixed array using the conditional type
const stringsArray: string[] = mixedArray.filter((item) => typeof item === 'string');

// Print the filtered arrays
console.log("NumbersArray:", numbersArray); // Output: [100,344]
console.log("StringsArray:", stringsArray); // Output: ['Red','Green','White']

Explanations:

In the exercise above -

  • We use the "filter()" method to create two arrays, 'numbersArray' and 'stringsArray', based on the condition specified in the filter callback function.
  • 'numbersArray' contains only numbers, and 'stringsArray' contains only strings from the 'mixedArray'.
  • Finally we print the filtered arrays, and you will see the expected results at runtime.

Output:

"NumbersArray:" // [object Array] (2)
[100,344]
"StringsArray:" // [object Array] (3)
["Red","Green","White"]

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript mapped type example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.