const list = ['rabbits', 'raccoons', 'reindeer', 'red pandas'] as const
const filteredList = list.filter(e => e.includes('re'))
How to type filteredList? I think of (typeof list[number])[], and TS is OK with this, but since list[number] is just a single item, the type is more like an array with repetitive items to me, e.g. ['reindeer', 'reindeer'] or ['red pandas', 'red pandas']. I'm not sure if that is correct?
Actually TypeScript infers
filteredListas type("rabbits" | "raccoons" | "reindeer" | "red pandas")[]which is equal to(typeof list[number])[]and I think it's totally okay to go with that.TypeScript Playground
If you wanted the most accurate type possible on
filteredListyou could use a custom helper type which filterstypeof listat compile time. Then assertfilteredListto that type. I came up with this inspired by this answer on Variadic Tuple Types by @jcalz.Essentially, you check if an item in
listis assignable to${string}${U}${string}whereUis your filter criteria (e. g."re"). If so, the item is kept in the resulting tuple type. If not, it is removed.TypeScript Playground