MediumPro challengeJavaScriptTypeScript

Distributive Conditional Types

TypeScriptTypesConditional Types

When a conditional type acts on a naked type parameter, TypeScript distributes it over each member of a union:

type IsString<T> = T extends string ? true : false;
type R = IsString<string | number>;
// → true | false   (applied to each member separately)

// The most famous distributive utility:
type NonNullable<T> = T extends null | undefined ? never : T;
type R2 = NonNullable<string | null | undefined | number>;
// → string | number

To prevent distribution, wrap in a tuple:

type Strict<T> = [T] extends [string] ? true : false;
type R3 = Strict<string | number>;
// → false  (the whole union is checked at once)

Your Task

Implement three runtime utilities that mirror distributive type operations:

FunctionBehaviour
filterUnion(values, type)Keep only values where typeof v === type
excludeNullish(arr)Remove null and undefined (mirrors NonNullable<T>)
flattenUnion(arr)Flatten one level: mixed `TT[]T[]`

Sample tests

Test #1keep only numbers
Input: ["filterUnion",[1,"a",2,"b",true],"number"]
Output: [1,2]
Test #2keep only strings
Input: ["filterUnion",[1,"a",2,"b",true],"string"]
Output: ["a","b"]
Test #3remove null and undefined
Input: ["excludeNullish",[1,null,2,null,3]]
Output: [1,2,3]
Test #4flatten mixed array
Input: ["flattenUnion",[1,[2,3],4,[5]]]
Output: [1,2,3,4,5]