An order object can simultaneously have paidAt?, cancelledAt?, and refundId?. Each field is optional, so the type system allows for an order that has been partially cancelled but is still partially paid, or that has been refunded but lacks a refund confirmation. Developers are not allowed to re-validate the combination in each function.
When business states have clear distinctions, it’s best to define these distinctions as separate types, rather than using a single, broad object to encompass all possibilities. Types are not responsible for creating the correct business logic, but they can help to reduce the free-flowing of invalid states within the code.
First, list all valid combinations of states.
type Order =
| { state: 'pending'; id: string }
| { state: 'paid'; id: string; paidAt: string }
| { state: 'cancelled'; id: string; cancelledAt: string }
| { state: 'refunded'; id: string; refundId: string };
This is a simplified model. Real-world business processes may allow orders to be canceled and refunded after payment, but this should be represented accurately, with the correct status or multiple independent dimensions, rather than being distorted for the sake of aesthetics. The list of statuses needs to be confirmed by the business, not simply guessed by engineers.
The discriminant fields allow the compiler to narrow the type within the branch. Before reading the refund flag, the status must be confirmed. The cancellation time should not be scattered among irrelevant statuses. When adding a new status, exhaustive processing can help identify missing page and service logic.
Allowed Actions Expressed by Transformation Functions
The payment function should accept pending orders and return successfully paid orders. This can prevent obvious and unreasonable state transitions within the local call. However, concurrent requests may still operate on the same old state object, and the type cannot guarantee the latest database state.
Therefore, persistent transformations require conditional updates, such as writing “paid” only when the database state is still “pending payment.” Type-safe code protects the internal shape of the database, while database condition protection safeguards concurrent operations, and together, they address different problems.
When an action fails, it should return a clear result, such as “status changed,” “order not found,” or “dependency failed.” Avoid treating all failures as non-payment orders and continuing execution, as this would make the static type appear correct while the actual state is different.
The function receives a pending object, which proves that the object’s shape was valid at that time. However, it does not prove that the database is still awaiting payment. Two callers can hold the same old object, and the database conditions determine who succeeds. The new paid object returned should come from the submitted result, and cannot be constructed and treated as a fact before the update. The type expression represents a business record and cannot be used to prematurely declare the business as complete.
The transformation function can restrict the input state and return explicit results, distinguishing between business rejection and system failures. A state change could represent legitimate competition, while database unavailability requires an alert and controlled error handling. It should not return the old “pending” state, forcing the caller to re-pay. External payment timeouts could also result in an unknown result, requiring the system to enter a “pending confirmation” or independent operation state. This realistic scenario should not be omitted for the sake of brevity.
A single state may not be suitable for all dimensions. Payment, fulfillment, and refunds can each have their own stages, and Cartesian products require business constraints, avoiding the need to list dozens of large combinations. If dimensions are independent and separate types; if there are key relationships, boundary validation and transformation logic should be expressed. The type model should reduce invalid combinations while maintaining practical business readability, and should not be used to prevent normal states from being represented for the sake of advanced techniques.
Parsing Unreliable Input First
Network JSON, old database records, and user input cannot be trusted simply because a type declaration has been written. as Order only tells the compiler to trust you; it does not verify that the fields actually exist. Boundary values require runtime parsing and validation to determine whether the fields contain the data required for each state.
When parsing fails, retain the error path and version information, but avoid writing complete sensitive objects to the logs. For historical records, provide migration or compatibility adaptations, but do not silently “fix” a current timestamp to make an old order appear legitimate.
Type narrowing should align with the actual state source. Once the fields are derived from the parsed record, the branches can safely access the corresponding attributes. However, simply submitting a successful status does not guarantee the actual business state. The domain construction entry restricts legitimate migration by not treating “shape compliance” as proof of payment.
The new network response state could originate from a server upgrade, and the internal domain model can strictly reject it. The external adapter layer, on the other hand, expresses unknown or erroneous values according to compatibility policies. It is not possible to force as to become a known union after reading a non-existent field. Historical database rows are missing refund indicators and should be migrated or isolated. Do not use random identifiers and current timestamps to fabricate false facts. Default values only apply to genuine business defaults.
Using patterns and types generated from a single source reduces redundancy, but relationships still need to be reviewed. The format of the time string being valid does not prove that paidAt exists after creation, nor does it prove that the refund identifier belongs to the order. Runtime validation first confirms the structure, then business rules confirm the meaning, and finally, authorization determines whether the operator can use it. These three steps cannot be combined into a single “safe” process simply because they were generated by a tool.
The error diagnosis retention field path and version, along with private payloads, are not logged publicly. The adapter layer outputs strictly defined domain objects, and pages do not need to check for database compatibility or empty values everywhere. During migration, the boundary can support both versions, and after completion, the old branch is removed to avoid permanent widening of the data types. Readability comes from a limited set of valid forms and clear conversions, not from an increasing number of optional fields.
Strict Categorization by Type
The domain layer should aim for complete and clear fields, while the UI layer may need to handle loading, failure, and empty results. The domain layer should not be solely responsible for managing all view states, as this would revert to a large number of optional fields.
It’s possible to define a separate result union for individual requests:
- Loading: No orders found.
- Success: Legitimate orders found.
- Failure: Displayable error.
This approach prioritizes processing the request status first, followed by the order status. This will result in a clearer reading path.
The types of database rows also don’t need to be directly exposed to the UI. The database allows for empty fields to facilitate migration, and the domain adaptation layer can validate and convert them into more strict objects. Centralizing the handling of empty values at the boundary is more maintainable than having each button check for database-compatible fields.
Avoid Branding All Strings
When order identifiers and user identifiers are easily misrepresented, brand types can help differentiate them. However, creating complex brands for each common string increases the burden of construction, parsing, and testing. Instead of focusing on the number of different brand types, the focus should be on mitigating the real risks of misrepresentation.
The brand also lacks runtime guarantees. External strings must be validated or constructed in a controlled manner, and cannot be used for arbitrary assertions. The team should agree on which modules are authorized to create brand values, to avoid the situation where type boundaries become purely symbolic.
When designing complex generic types, it’s also important to consider the readability of error messages. A simple, unified type system doesn’t necessarily require deep conditional types. The consumers of type design include future maintainers and test authors, not just the compiler.
When a switch handles state transitions, using never to check for missed cases ensures that new states trigger a compilation error. Pure presentation components can have limited mapping, and any unknown external input is handled in the adapter layer first, preventing each component from masking internal omissions with a default value. The compilation error should indicate which decision needs to be updated, rather than requiring all modules to understand the entire business state.
The brand ID is suitable for calling points where order and user parameters are easily confused, and it constructs an entry execution format or source check. The brand is simply a compile-time label and does not prevent malicious strings. Runtime verification is still performed. Test cases use legitimate constructors to create values, and assertions are not used in all examples to verify whether the boundaries are well-behaved. If a large amount of normal business requires forced assertions, the model or interface responsibility may be unreasonable.
Data types and database schemas do not necessarily need to be identical. Databases may store data in a way that is compatible with objects that can contain null values, while domain objects strictly represent the current valid state. DTOs (Data Transfer Objects) are serialized to express external compatibility protocols. By using separate naming and adaptation mechanisms, we avoid a single type having to fulfill three different responsibilities. Adding explicit conversion code is often more maintainable than relying on a single, all-encompassing structure.
Model Evolution Needs to Consider Both the Caller and the Data
After increasing the “pending payment” status, changes to services, interfaces, background tasks, and serialization may be required. Internal exhaustive checks help pinpoint code issues, and compatibility between the database’s old records and external clients still needs to be maintained at runtime. The disappearance of type errors does not guarantee that the old client can understand the new status; contract testing and version agreements provide an additional layer of assurance. Each boundary should clearly define how unknown scenarios are handled, without allowing any single mechanism to cover everything.
The string values for the status fields can be limited to a finite set, but the error codes do not need to be coupled to all page text. Domain status descriptions provide factual information, view status descriptions describe loading and display, and error result descriptions explain the reason for the operation failing. After separating these, the page first confirms the success of the request before reading the order, to avoid mixing loading and database fields within the order object. The type name service responsibility should not be merged into a single concept to reduce the number of statements.
Permissions for creating objects can also be centralized. Boundary parsers, trusted database adapters, and legitimate transformation functions can generate domain values, preventing ordinary users from arbitrarily constructing them. TypeScript cannot prevent malicious JavaScript at runtime, but the team structure and testing reduce the risk of unintended side effects. Encapsulation provides real complexity benefits, without adding excessive empty wrappers for type-level tricks.
The test examples include both valid historical payments, refunds, and cancellations, to ensure that the simplified model does not exclude real-world business scenarios. If a state can retain the payment time as historical evidence, it should use the correct field to represent it, rather than deleting the historical fact simply because the current state is not “paid.” States represent the current stage, while event history represents what has already occurred. These can exist independently. A union type is not a substitute for database audit history.
It is also important for maintainers to be able to understand error messages. In cases where deep generics cause difficult-to-understand compilation errors, simple unions and explicit functions may be more appropriate. A well-defined domain boundary expressed using several valid objects often proves to be more effective than a generic state machine framework. When evaluating the maturity of a design, prioritize common misuse, team understanding, and runtime contracts, rather than simply counting the number of type features.
Clearly Expressing Concurrent Competition in the Results
The “pending” order is not a permanent pass. The user interface reads “pending,” and a background task then cancels the order, and the page resubmits the payment. The payment function receives a valid object shape, but it’s outdated. It can return a limited set of results, such as “committed,” “state-conflict,” “not-found,” or “dependency-failure,” while the successful branch carries the actual committed order. When the caller encounters a conflict, it re-reads and interprets the current state instead of continuing to use the old object.
If the database supports row versioning, you can include the expected version along with the status in the conditional update. After the number of affected rows is zero, you can query the reason accordingly. This mechanism controls local state conflicts, but it cannot perform atomic control over external payment providers. If a payment has already been issued but the conditional update fails, a business coordination process is required, rather than assuming that the funds have not changed simply because the TypeScript result is a conflict. It is important to clearly define the boundaries between domain state, external operation state, and local transaction state.
The example conversion can move from “pending” to “payment-confirming,” and then to “paid” or “explicitly rejected.” The “pending” state carries stable operational indicators and a start time, but not a random “paidAt.” The new state provides genuine entry points for the page, background tasks, and customer service, but also increases the responsibility for recovery: who to contact the supplier, when to escalate the issue, and how to continue after restarting the process. The value of this type is that this responsibility cannot be eliminated in a simple boolean value.
Action functions should also not rely on the caller checking the state to ensure safety. There is a concurrent window between checking and execution, and the persistence layer must re-validate. Disabling the payment button on the front end is simply an interaction optimization, not authorization or protection against competition; users can directly call the interface. Types, runtime input, and database conditions cover misuse, malicious input, and factual competition, and the design should maintain these layers in a complementary manner.
Separate the state from the historical facts
The order is currently marked as “refunded,” but this does not mean it was never paid. An audit may require information about the original payment time, the vendor’s actions, and the refund time. If the “refunded” type is only allowed to have a refundId and lose the paidAt value during conversion, then the type sacrifices necessary historical information for simplicity. We can keep the stable order identity and immutable historical facts in a common part, while the current state branch only expresses the capabilities specific to that stage. Alternatively, we can use independent event records and select them based on the query requirements.
Historical events still require reliable sources and access control. A client submitting a paid event cannot prove payment; the backend parser only verifies the structure. A trusted adapter is required to verify the source. The event timestamp may also differ from the recorded timestamp, and cannot be automatically replaced with the supplier’s confirmed timestamp. The type field can express both and explain the purpose, to avoid page sorting or auditing mixing different facts into a single timestamp.
The status categories should correspond to business decisions, not simply replicate all technical events. Starting a network connection, establishing a connection, and receiving a response header typically fall under diagnostic actions and should not be treated as a long-term order status. “Payment pending confirmation” should affect whether a user can perform further actions, and is suitable as a domain status or independent operation status. The distinction should be based on the actions that the caller needs to take, rather than requiring all observations to be unified.
Maintain unknown branches for external protocols, but avoid polluting the entire internal logic.
The internal service now includes a “chargeback” status, which is not recognized by older browsers. A thorough check of the internal code can force maintainers to update, but browsers that have already been deployed will not be recompiled. External DTOs require a version policy; older clients should be able to display an “unsupported” status and re-fetch information, without automatically interpreting unknown values as “pending.” Unknown states should not expose previously restricted actions.
The adapter can convert known external states into a strict domain union, and return controlled protocol results for unknown code. Domain business functions only receive values that have been converted, and pages do not need to compare arbitrary strings everywhere. The “unknown” in the compatibility layer represents a real boundary strategy, while the “default” in the domain’s internal switch often simply represents a missed or hidden case; although they appear similar, they have different responsibilities.
When serializing, avoid directly expanding the entire domain object. The paid field might contain internal payment records, risk assessments, or audit identities; the browser only needs the public order fields. Define explicit DTOs and test the output keys, but this doesn’t mean that fields are suitable for public exposure. Even if a property is marked as private in TypeScript, you shouldn’t blindly trust that the original runtime object will be invisible when serialized to JSON.
Using a Sample Compile Interface to Test for Intentional Failure
The example for compilation should verify a real misuse case: passing pending to the refund function, reading refundId from cancelled, treating the user ID as the order ID, and expecting an error. The example must participate in actual type checking and cannot be hidden within directories excluded during build. It should use expected error markers supported by the tool, allowing for testing failures when future type widening causes the error to disappear.
Re-validate whether the correct path is actually usable. A business process needs to pass ten consecutive times to be considered valid, which usually indicates that the boundaries are not well-defined, the types are overly generalized, or the state facts do not match. Instead of assuming that this is due to poor developer discipline, it’s important to return to model checking. The test author should use public entry points instead of ad-hoc assertions, which can also reveal whether the encapsulation is convenient.
Runtime example coverage demonstrates inputs that appear similar but have different meanings: “legitimate, refunded” (missing required identifiers), “unknown status with payment field,” and “string date format correct but not in business order.” Parsing, relationship validation, and permission checks all fail at distinct points. The error returns the path and category, but does not copy the entire payment record to the log. This type system effectively reduces internal guesswork without giving external inputs false trust.
The evolution of the type also requires checking the old payloads in the persistence queue. When new code reads the old state, it should either be converted by a versioning adapter or explicitly rejected to prevent retry tasks from continuously crashing. After the migration, the compatibility branches should be deleted, and it should be confirmed that the old deployments no longer write in the old format. Completion of source code compilation and data migration are two acceptance points, and neither can be completed individually by the team.
Acceptance Includes Compilation and Execution
Create compile-time examples to verify that orders awaiting payment cannot read refund indicators. Adding a new state should cause the “exhausted” handling to fail. Then, use runtime tests to send in orders with missing fields, unknown states, and old versions of objects, to confirm that parsing clearly rejects or performs controlled conversion.
Finally, concurrent attempts to initiate payments and cancellations are validated, ensuring that the database only accepts legitimate conversions. Static typing, runtime validation, and persistence constraints form complementary defense layers, and no single layer should be considered a replacement for the other two.
The value of using types lies in making common errors more difficult to express and making the correct path easier to read. If a team is using assertions throughout the design to circumvent issues, they should re-evaluate whether the model accurately reflects the actual business requirements.
The compilation test uses expected error assertions to confirm that invalid field access actually fails, rather than simply bypassing type checking. The test coverage includes missing fields, unknown states, and historical adaptations. The database test covers payment cancellation concurrency. Finally, the assertions are reviewed to ensure that any bypasses of the “any” clause do not invalidate type guarantees. Type design is only meaningful when tested with real inputs and persistent facts.