MediumJavaScriptTypeScript

Utility Types — Extract & Exclude

TypeScriptUtility TypesUnions

Extract<T, U> keeps only the members of union T that are assignable to U.
Exclude<T, U> removes from T those assignable to U.

Implement filterByType(values, type) at runtime — it takes an array of mixed values and a type string ("string" | "number" | "boolean") and returns only the values of that type.

Examples

  • filterByType([1, 'a', true, 2, 'b'], 'number')[1, 2]
  • filterByType([1, 'a', true, 2, 'b'], 'string')['a', 'b']
  • filterByType([1, 'a', true], 'boolean')[true]

Sample tests

Test #1filter strings
Input: [[1,"a",true,2,"b"],"string"]
Output: ["a","b"]
Test #2filter booleans
Input: [[1,"a",true],"boolean"]
Output: [true]
Test #3filter numbers
Input: [[1,"a",true,2,"b"],"number"]
Output: [1,2]