Can you use a discriminant that isn't a string literal, like a number or boolean literal type?
Short answer
Yes — the discriminant just needs to be a literal type (string, number, or boolean literal) that's unique across the union's variants; TypeScript narrows equally well whether you check with ===, a switch, or even truthy/falsy checks on a boolean discriminant.
Advertisement
AModel answer
Yes — the discriminant just needs to be a literal type (string, number, or boolean literal) that's unique across the union's variants; TypeScript narrows equally well whether you check with ===, a switch, or even truthy/falsy checks on a boolean discriminant.
type Success = { ok: true; data: string };
type Failure = { ok: false; error: string };
type Result = Success | Failure;
function handle(result: Result) {
if (result.ok) console.log(result.data); // Success
else console.log(result.error); // Failure
}Real-world example
Using a simple boolean 'ok' discriminant for a lightweight Result<T> type, common in functional-style error handling.
Likely follow-ups
- Would using a plain 'boolean' (not the literal 'true'/'false') type work the same way as a discriminant?
Related topics