Ideally I'd want an explicit false
when there's no error and exclude all Falsy values from error when there is an error:
type Result<T, E> = { result: T; error: false } | { result?: T; error: E }
type User = {
name: string
}
export const someFunction = (): Result<User, string> => {
if (Math.random() > 0.5)
return {
error: false,
result: {
name: 'John',
},
}
return { error: '' } // I'd want an empty string to not be allowed
}
const someOtherFunction = () => {
const { error, result: user } = someFunction()
if(error === false) { // I'd want all Falsy values to be excluded from E, so I could have a clean type guard: if(error)
return
}
console.log(user) // User | undefined, given there's no error, should be User only
}
someOtherFunction()
But this doesn't work How can I exclude all Falsy values from my right-hand side error
in a way that makes the destructuring assignment work cleanly?
Here's a minimal reproducible example.