Hacker News new | ask | show | jobs
by domlebo70 1036 days ago
To OP: You could avoid the visitor by using an IIFE style switch using the run utility fn:

    export const run = <T>(f: () => T): T => f();
Now you can go:

    const inferred_type = run(() => {
      switch(blah) {
        ...
      }
    })
2 comments

Exactly! I wrote a post about this pattern: https://maxgreenwald.me/blog/do-more-with-run
Yeah this is where I heard about it :P I showed all my dev friends, and our minds were equally blown away by the obviousness of it.
You don't even need to do this much, you can just invoke the function and let the return type be inferred.

  const inferred = (() => "Hello")() // Inferred as "string"

If you really don't want to use an IIFE because you don't like the "()" at the end, you can just:

  const myFn = () => { switch(...) }
  const inferred = myFn()