4 ms·
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:
by domlebo70 3y 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) {
...
}
})
- mgreenw 3y agoExactly! I wrote a post about this pattern: https://maxgreenwald.me/blog/do-more-with-run https://maxgreenwald.me/blog/do-more-with-run
- domlebo70 3y agoYeah 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.
- gavinray 3y agoYou 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()