Defining the type of Result
has presented some challenges for me. It should adhere to one of the following patterns:
type Result<Some> = { code: 0; some_result: ...}
// or
type Result = { code: NonZero; message: string}
How can I properly type this?
Perhaps, this question can be broken down into two parts:
- Developing
NonZero
(note thatExclude<number, 0>
doesn't seem to work) - Providing typings for the generic
Result
Updates
I have crafted a functional snippet as shown below:
type Result<TCode extends number, T extends {} = {}> = TCode extends 0
? { code: 0; } & T
: { code: TCode; reason: string };
type SomeResult = {some_result: string}
function getSomeResult(): Result<0 | -1 | 6007 | 114514, SomeResult> {
return {
code: 0,
some_result: ''
}
}
const result = getSomeResult()
switch (result.code) {
case 0:
// this is wrong: reason should be void
result.reason
// this is ok:
result.some_result
break
default:
// this is ok: there's always a reason when code is non-zero
result.reason
}
Currently, the TS compiler is able to deduce that the other property defaults to void. Nonetheless, I am required to specify all potential non-zero values for code
as a type parameter.
What's the best way to type NonZero
?