#Narrowing using `.filter()` without duplicate predicate

4 messages · Page 1 of 1 (latest)

gleaming nest

Is there a cleaner way to do the following where the type of array automatically becomes narrowed Discord.Collection<string, TextBasedChannel>?

I am aware that I can do

const array = mybot.channels.cache.filter((t) : t is TextBasedChannel => t.isTextBased());

But to me that sort of defeats the purpose of having a function that already does the narrowing. Is this just a limitation of Typescript that narrowed functions as return values don't bubble the type? Seems like it doesn't work unless the function signature being passed to filter() is the one that narrows

If you do:

for (const chan of mybot.channels.cache.values()) {
  if (chan.isTextBased()) {
     // narrowed
  }
}

This also has the desired effect

sharp skyBOT
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!
carmine oriole

I think Typescript 5.5. finally infers the type there

gleaming nest

ah! nice. still waiting on the eventemitter issue to swap over but that'll be good to test. thank you!