All notes

TypeScript Needs Runtime Validation at Network Boundaries

Parse unknown values, preserve update intent and separate safe feedback from internal diagnostics.

English edition, edited for length. Read the complete Chinese original.

The interface declaration returns User, while the actual response contains the age as a string. The code compiles successfully until the sorting results show an error. TypeScript checks the type relationships in the source code, but it does not verify the network bytes. Adding an assertion for external values will only cause the compiler to stop asking questions.

A reasonable boundary strategy is to initially treat all external inputs as unknown and then, after runtime validation, proceed to execute strict domain code. The validation should be focused and explicit, without requiring every internal function to repeatedly check the same object.

Handling Unknown Values in the Entry Parsing

const raw: unknown = await response.json();
const user = UserSchema.parse(raw);
return buildProfile(user);

The pattern should at least express field types, required values, and allowed ranges. A string does not necessarily represent a valid identifier, and a number does not necessarily represent a non-negative integer. Business rules should be implemented based on real-world constraints, but should not restrict the set of characters allowed for names or arbitrarily guess the maximum length without a valid basis.

After successful parsing, the returned object should be in a shape that the business code can trust. If the pattern allows for unknown fields, it should be explicitly defined whether to retain or discard them, to prevent internal management fields from being directly passed to the database after being submitted by the user.

Type assertions are not transformations: raw as User does not convert the age from a string to a number, nor does it delete isAdmin. The serialized Date is no longer a date object, and the corresponding bigint values still require a specific protocol. Boundary types should describe the actual transmission shape, and then obtain the internal model through controlled transformations. You cannot directly apply the TypeScript type of a database entity to an HTTP response.

Regarding update interfaces, the handling of unknown fields has implications for both security and compatibility. Rejecting unknown fields can help detect client typos early on, while discarding them allows for tolerance of version differences. Preserving unknown fields is suitable for certain data passing protocols. However, each of these options should be clearly defined, but when saving user input, a field whitelist must be used, and the entire parsing object should not be expanded into a database update statement. A valid role: "admin" structure does not necessarily mean that the caller has the right to set it.

Avoid Ambiguity: Distinguish Between Conversion and Verification

Converting string numbers to integers can improve the configuration experience, but it introduces semantic considerations. Are empty strings, whitespace, text with units, and scientific notation allowed? If the conversion rules are too permissive, misconfigurations could be interpreted as valid but unexpected values.

First, verify the text format. Then, perform the controlled conversion. Finally, check the range. Date formats also require defining both format and time zone, and should not rely on lenient parsing of various strings at runtime. The convenience of boundaries should be a clear agreement, not an assumption of user intent.

Default values should also be handled with caution. When a default pagination size is missing, providing a reasonable default value is safe. However, using an empty string when the database password is missing is dangerous. It’s important to distinguish between missing, explicitly empty values, and invalid values. Default values should not be used as a way to hide configuration errors.

Assuming the port configuration comes from environment variables: Number("") results in 0, and Number(" ") also results in 0. If the pattern only checks for “numeric”, invalid input passes. A more controlled process would be to first confirm that the string is not empty and conforms to the allowed decimal format, then convert it, and finally check if the integer falls within the specified port range. Whether scientific notation is allowed is not a technical matter of right or wrong, but rather whether the configuration protocol promises to support it.

The numerical limits also need to consider precision. Order numbers that exceed the JavaScript safe integer range cannot be safely used simply because of typeof value === "number". Identifiers are typically suitable for storing strings; amounts require a clear definition of the minimum currency unit, precision, and rounding rules. Runtime validation checks whether the agreed-upon rules are being followed, but it cannot fix a data model that lacks a defined precision.

Configuration validation can be performed centrally during the startup phase. The original environment variables are parsed into immutable configuration objects, and business functions only receive validated fields. If the required service address is missing, the process fails immediately, making it easier to pinpoint the issue than waiting for the first user to trigger a branch. The error message indicates the variable name and the corresponding rule, but does not reveal tokens, passwords, or the complete connection string.

Clear attribution of cross-field constraints

The rules that “start time is earlier than end time” and “refund amount is less than or equal to the payment amount” cannot be expressed as individual field types. Structural validation can handle relationships within objects, while rules involving the current state of the database require validation by business services.

It’s not possible to make uncontrolled network calls during pattern parsing, which would hide external dependencies and make a seemingly pure validation function. Instead, the structure parsing and business eligibility judgment should be separated, allowing for clear explanations of error types and performance costs.

Reading data from the database can also be unreliable, especially when dealing with old versions of records, manual modifications, or multi-language entries. The adapter layer can check necessary invariants, isolate and alert on invalid historical data, and prevent the error from being silently propagated to the page.

Structural validity and business rules require a layered approach. For example, the amount entered for a refund must be a positive integer, which falls under structural and range validation. The amount must not exceed the remaining balance, which depends on the current database state. Also, the caller must be authorized to make the refund, based on whether they are the tenant of the order. If the remaining balance is checked before executing the refund, concurrency issues must also be considered, so the final constraint should be enforced within a transaction or conditional update. Parsing the schema does not guarantee that the entire request is safe.

When historical records require compatibility with legacy paths, you can use explicit version fields to differentiate between old and new patterns, and then convert them to the current internal representation. Avoid making all fields optional in a relaxed mode and then guessing which version the record belongs to. Records that cannot be reliably migrated should be isolated and traceable, and should not be filled with fabricated default values to make reports appear complete.

Feedback on errors has two audiences

Users need to know which input fields can be modified, and engineers need to know where external protocols change. It’s important to retain field paths and error categories to avoid directly outputting the complete original values. Passwords, tokens, and user data should not be logged if verification fails.

The interface should return stable error codes and human-readable messages, avoiding reliance on the native error text from the underlying validation library. Changes in wording after library upgrades should not be interpreted as changes to the external protocol. Internal diagnostics should be able to store version information and failure paths, facilitating troubleshooting.

For bulk input, you need to decide whether to reject all entries or process them individually. Both approaches are reasonable, but you should not silently filter out bad rows and claim success after a parsing failure. Users need to know which data was accepted and which needs to be fixed.

Error codes should distinguish between format errors, structural errors, business conflicts, and changes in external protocols. Information such as the user’s return of INVALID_AMOUNT, the internal record pattern version, field paths, and request association identifiers is usually sufficient to pinpoint the issue. If you need to retain error samples, first define de-identification, access permissions, and retention periods. Avoid allowing the validation layer to become a hidden system for archiving original requests.

Large inputs still face resource constraints. The validator will not automatically limit HTTP requests, array lengths, nesting depth, and expensive regular expressions for you. Instead, set reasonable sizes at the ingress layer and then validate the business shape. For bulk imports, allow users to understand and split tasks; clearly reject tasks that cannot be processed, and avoid exposing errors only after the process has consumed all memory.

Pattern Reuse Requires Awareness of Boundaries

Creating, updating, and displaying users do not necessarily require the same pattern. Creating a user requires a password, but displaying a user does not allow password retrieval. Updating a user allows modification of certain fields, but should not allow modification of administrator privileges. Reusing a single, universal pattern throughout the system can expand permissions and increase the scope of potential vulnerabilities.

Stable field definitions can be shared, and then combined to create different input/output patterns. The more the patterns align with specific capabilities, the easier they are to review. Database entity patterns should not directly become public API patterns; internal field evolution requires an isolation layer.

The type generation approach helps reduce redundancy, but it’s crucial to ensure that the generated optional and null values align with the intended usage of the code. Since some of the transformed output types may differ from the input types, the function signature should clearly reflect the actual stage of transformation.

The output also warrants verification, but the verification methods differ. The response patterns of external interfaces should be confirmed during testing or runtime to ensure that internal fields are not returned. For vendor adapters, the received data should be validated. For performance-sensitive links, it’s necessary to measure the parsing cost before deciding whether to perform redundant verification. It’s not advisable to completely skip untrusted inputs to save on minor overhead, nor is it necessary to repeatedly parse the same object by already validated internal functions.

In the “No Change” and “Value is Empty” modes, the distinction can be easily confused. The former typically indicates maintaining the current state, while the latter might indicate clearing the field. Standardizing both to “undefined” would prevent users from deleting values; setting missing fields to an empty value could clear existing data during local updates. The request and update constructs should preserve this intent.

The update agreement should retain the different intentions of missing values, null values, and cleared values.

Users only modify the nickname, and the “phone” field is not present. This usually indicates that the phone number is being retained. A “phone” field that is null may indicate that the phone number has been cleared. An empty string for the “phone” field may represent invalid input, or it may be explicitly normalized to an empty string according to a specific rule. These three scenarios must be distinguished during parsing and update operations. If missing “phone” values are defaulted to an empty string, local updates may unintentionally delete data. Convenient conversion must adhere to the actual protocol, rather than attempting to parse all values successfully.

Update objects are constructed solely from allowed fields. Even if a schema discards unknown fields, it should not directly expand the schema output into a generic database update, as new output properties could expand the writable range in the future. Creation, updating, and displaying have separate capabilities, and field rules can be reused, but a single, universal entity cannot be used for all commands. Field validity and operator-defined fields are checked independently.

When updating arrays in bulk, it’s crucial to clearly define how duplicate IDs are handled. Whether to reject, merge, or execute sequentially for two entries modifying the same order needs to be predetermined, and cannot be decided randomly based on the order of overriding in the object dictionary. Even after successful parsing, the overall business constraints may still fail; structural validation is not responsible for ensuring database consistency. Transactions and conditional updates ultimately enforce a final, consistent state.

Prioritize Resource Constraints Before Expensive Validation

A valid JSON document can still contain large arrays or deeply nested structures. The entry layer first restricts the actual number of bytes read, and cannot rely solely on the Content-Length header. After compression, the input data also needs to be decompressed before the byte count is limited. Parsers, runtime validators, and business logic all have their own costs, which are limited by the existing mechanisms on the platform. The schema’s maximum size is not automatically enforced before parsing to protect memory.

Regular expressions can also introduce complexity risks. When validating, focus on common edge cases and long, invalid strings. Prioritize using standard parsers or simple, explicit rules, rather than trying to cram an entire complex protocol into a single regular expression. For URL, date, or email validation, distinguish between syntactically valid, business-allowed, and actually accessible resources. The latter should not involve making hidden network requests within a single validation function.

Error aggregation requires a limit. A million invalid entries cannot generate a million detailed error messages and then return them; batch protocols can limit the input size, report a certain number of errors, and indicate truncation, or use controlled asynchronous import tasks. Truncated diagnostics do not mean silently accepting bad lines; overall acceptance and rejection rules must be clear. Users should know how to split and fix, rather than receiving a process crash.

Establishing Clear Steps for Version Compatibility

Previously, suppliers represented amounts as strings, while the new format uses the smallest unit as an integer. Even though both formats can be converted to numbers, they should not be placed in the same loose field and guessed based on the unit. Choose a parser based on the reliable version or protocol identity, and convert them to an internal amount model, and test equivalent results for the same business amount. If there is ambiguity or missing version, explicitly reject or coordinate. Do not guess based on the numerical size.

Persistent records can carry version information, and adapters read older versions and convert them. If historical information is missing and cannot be reconstructed, the system returns to a controlled unavailable state or schedules a migration. This involves omitting the current time, a random identifier, and fabricating default currency information. The migration report includes the number of records that have been converted, those awaiting verification, and those that have been rejected. It is important to note that the report cannot be used to falsely claim complete success after filtering out invalid records.

Compatibility does not require indefinite retention. After stopping old writes, confirming old deployments and queue loads have exited, and migrating historical data, the old parser should be deleted. Type definitions only describe the current code; persistent input may span multiple versions. Read boundary testing uses real, old samples, with sensitive fields replaced by legitimate synthetic values, while preserving structure and relationships and not duplicating production private records.

After parsing, further check for semantic consistency and source accuracy.

A “paid” status and valid timestamp only indicate that the shape conforms, not that the supplier has actually made the payment. External callbacks require verification of the source, signature, and non-repetition, and the business service confirmation operation is a valid order. A positive integer does not necessarily mean that the currency and order balance are consistent. The pattern is responsible for the structure, a trusted source is responsible for the factual identity, and persistent conditions are responsible for the current executability. You cannot simply call this “verification successful” and skip the subsequent steps.

The file path is the same. A valid string does not mean it can be read; the normalized path still needs to be constrained within an allowed range. Successful URL parsing does not mean the server can access it; the network exit also needs to have target policies. The validator outputs a URL object, which provides a structured value for the next layer, but does not grant any network capabilities. The boundaries of these capabilities are again enforced at the point of actual resource access.

Output validation serves different purposes depending on the service’s objective. Public APIs expose explicit fields, while contract testing verifies the absence of internal properties. Vendor adapters validate the input. Pure internal functions, once they receive already validated objects, generally do not re-parse them, as this would increase costs without providing clearer responsibility. If a module can be called independently and has different input sources, its public entry point can be validated, along with a clear statement of the trust range.

Using a Small Set of Counterexamples to Validate Rules Won’t Subtly Change Them

Creating counter-examples for text-to-number conversion: missing values, empty strings, whitespace, negative numbers, decimals, scientific notation, extremely large integers, and values with units. For each example, state the reason for allowing or rejecting the conversion, and then verify that the results are consistent after upgrading the library. The string examples cover combinations of characters, encoded bytes, and invisible characters. The rules are based on the intended use of the field and do not uniformly truncate or convert to lowercase all content.

Also, test the output type and values after the conversion. For example, if you input a time text, you get an absolute moment, and when you serialize and return it, the approximate time zone meaning is still preserved. If a field is missing, it uses a default value, and any invalid values are still rejected. Only checking that the parse does not throw an exception is not enough to prove that there is no loss of intent during the conversion. The reliable boundary comes from these explicit agreements, rather than relying on a popular validation library.

When the review mode changes, review consumers simultaneously. For example, changing a required field to an optional one might allow old, invalid data to be parsed successfully, but it could also cause internal functions to repeatedly handle null values. If the compatibility requirements only apply to adapting older versions, they should remain within that boundary, rather than permanently widening the current domain type. The parser should focus on resolving uncertainty and then output clearer internal conventions.

Acceptable and Unacceptable Edge Values for Validation

For example, regarding usernames: whether empty strings are allowed, whether leading/trailing whitespace is trimmed, and how combined characters are counted, these should be clarified based on the product rules. The string.length restriction counts based on UTF-16 code units, which may not equal the number of characters seen by the user. If the restriction is for database byte capacity, check the encoded bytes. If the restriction is for a better user experience, use character segmentation that aligns with display requirements. Do not try to satisfy all goals with a single, unspecified maximum length.

The order in which inputs are normalized also affects identity. Email addresses, usernames, and file paths all have different rules, and they should not be uniformly converted to lowercase or normalized using Unicode. For inputs used in signing or auditing, the responsibility for maintaining the original and normalized forms should be separate. The more the validation rules adhere to the actual protocol, the less likely it is that two different inputs will be mistakenly treated as the same object.

The testing process can be structured with three columns: input, result, and reason.

null: Why is it rejected? Why is an empty value not the default? Why are extra permission fields not saved? These can all be inferred from the rules. Subsequently, run the process with real request encoding to confirm that the combination of content parsing, pattern validation, and error mapping still complies with the agreed-upon standards. Unit tests that only call pattern functions cannot cover the limitations of the access layer size and response obfuscation.

Maintaining the pattern also requires ownership. Changes to the pattern are managed by the adapter, while changes to the public API are reviewed by the interface owner. Compatibility with historical records is the responsibility of the data migration path. A shared pattern file will not automatically resolve cross-team protocol management. When a reader sees a pattern, they should know which boundaries it applies to, and which guarantees it does not cover.

Test for missing fields, null values, unknown fields, extremely large numbers, duplicate identifiers, and Chinese characters and combined characters. For each transformation, the validation process should not discard invalid values; and for sensitive fields, the error logs should not reveal the original values.

Furthermore, intentionally changing the type of response from the vendor should ensure that the adapter layer immediately identifies and reports errors, rather than only displaying them after several pages have been processed. The validation process is not intended to ensure that all data can be “parsed,” but rather to establish clear and reliable boundaries.

Finally, verify that the internal functions are no longer performing redundant parsing everywhere. After boundary consolidation, the internal code should be simpler. If the validation layer hasn’t reduced ambiguity, then it’s necessary to re-examine whether the patterns and domain types are consistent.

It is also possible to establish a set of stable contract samples that cover the missing and newly added optional fields in older clients, the additional fields in new clients, and the precision differences and conversions in the output. When upgrading the schema version, run the same set of samples to confirm that the changes are intentional modifications to the protocol, rather than the default behavior of the validation library. The ultimate reliance of trust boundaries is on clear data agreements; the schema tool is simply a means of enforcing these agreements.

References