3 ms·
I do it the "go" way, with: type Result<K = any, T extends Error = Error> = [K, null] | [null, T]; And use it: const [response, error] = await tryFetch<T
by rickstanley 4y ago
I do it the "go" way, with:
type Result<K = any, T extends Error = Error> = [K, null] | [null, T];
And use it:
const [response, error] = await tryFetch<Type>("");
if (error) { handle(); }
- macrael 4y agoBut this way you are losing the type checker yelling at you if you try and use response without having handled error. What I like about res = something(): Thing | Error is I have to do if (res instanceof Error) { handle() return res } doSomethingWith(res) or else the compiler will yell at me for trying to doSomethingWith(Error)
- rickstanley 4y agoI see. Well, for what it's worth, in my tuple example, you either have one or the other, i. e. the K result or an Error; so, if you don't check for error (or result), the compiler gives an error saying that "K is possibly `null`". Example: https://tsplay.dev/w2p0Vm https://tsplay.dev/w2p0Vm
- macrael 4y agothat makes sense, and I like the simplicity of `if (err)`. I'm sure it's uncommon but you still lose the compiler check if the function can return null as a matter of course.