RSS Amplifier

etoxin · Nov 2, 2021

Type guard a filtered array with TS user-defined type guards.

0
Sign in to vote or save

Adam Lusted · etoxin

Type guard a filtered array with TS user-defined type guards.

When you filter a mixed type array, the new typing is not passed to the new array. In the example below the returned type of the array is `(string | number | boolean)[]

const arr = [123, true, "I'm a string"];
// Normal filter
const normal = arr.filter((pred) => typeof pred === 'number');
// normal is `(string | number | boolean)[]` 

With the User-Defined type guards (pred is number ) our filtered list is correctly typed to number[]

// Filter using User-Defined Type Guards
const withTypes = arr.filter((pred): pred is number => typeof pred === 'number');
// withTypes is `number[]`

Read the original on etoxin.net

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.