I have a union type with discriminated properties:
type Status =
{ tag: "Active", /* other props */ }
| { tag: "Inactive", /* other props */ }
Currently, I need to execute certain code only when in a specific state:
// At some point
const status: Status = …;
// Later on
if (status.tag !== "Active") {
throw new AssertionError(…);
}
// Now I can be confident that `status` is of type "Active"
Is it possible to refactor the condition into an assert function?
// Somewhere
const assertStatus = (status: Status, tag: Status["tag"]) => ???
// And later:
assertStatus(status, "Active");
// Here I am sure `status` is of type "Active"