TypeScript / Advanced / Lesson 21
Versioned data contracts and normalization
Normalize explicitly versioned external data into a stable internal model while validating and testing migration assumptions.
On this page
Lesson goals
- Distinguish a wire version from an internal domain model.
- Normalize known variants using a discriminant.
- Test defaults, rejected versions, and migration behavior.
- Decode supported wire versions before normalizing to a stable internal profile.
- Test explicit migration defaults, unsupported versions, and rollback assumptions.
Separate representation from meaning
External data evolves, but allowing every internal caller to branch on every wire version spreads migration decisions throughout an application. Define a stable internal model and a boundary adapter for each supported representation. In this example version 1 has a name while version 2 has displayName and active. The choice that old profiles default to active is a domain policy, not a conclusion the type checker can derive.
Normalize known variants
A literal version tag allows a switch to narrow the union. The adapter converts either known variant into the same internal Profile shape. Its input type assumes that runtime validation has already established the wire shape; it does not validate raw JSON. When introducing a new version, define how each missing or renamed field maps to the internal model and review whether an inferred default changes real user behavior.
type V1 = { version: 1; name: string };
type V2 = { version: 2; displayName: string; active: boolean };
type Profile = { displayName: string; active: boolean };
function normalize(input: V1 | V2): Profile {
switch (input.version) {
case 1: return { displayName: input.name, active: true };
case 2: return { displayName: input.displayName, active: input.active };
}
}
The version discriminant selects the matching fields and returns one internal shape.
Compare old and new inputs
The two examples represent the same display name but different sources for active. Version 1 uses the explicitly chosen default; version 2 retains its supplied value, including false. Do not use a truthiness fallback for a Boolean field, since that can erase a meaningful false. Keep the code blocks in the same TypeScript file and verify the expected normalized objects through assertions rather than relying on display formatting.
const oldProfile: V1 = { version: 1, name: "Ada" };
const newProfile: V2 = { version: 2, displayName: "Ada", active: false };
console.log(normalize(oldProfile));
console.log(normalize(newProfile));
The old variant receives the stated default; the new variant preserves false.
Validate and reject unsupported versions
At the actual input boundary start with unknown and validate the version tag and every required field before calling normalize. Reject or quarantine unsupported versions according to a documented operational policy; pretending an unknown version is the newest can silently misinterpret data. Record safe diagnostics such as the version identifier and failure category, not an entire private profile. If multiple producers exist, coordinate the supported-version window and removal plan.
Verify migration and rollback
Create fixtures for each supported version, absent fields, wrong types, unknown versions, and the meaningful false value. Confirm that equivalent records produce the intended internal behavior and that invalid data never reaches the adapter. Test old readers and new producers during a staged rollout, including rollback and stored messages that outlive a deployment. Compile-time exhaustive checks help when the known union changes, but runtime validation handles values outside that union.
Separate wire representation from internal meaning
Versioned data contracts let producers evolve a representation while consumers preserve a stable internal model. In this lesson, version 1 carries name, while version 2 carries displayName and active. The internal Profile has displayName and active. The example policy maps a version 1 name to displayName and defaults active to true; version 2 preserves its supplied active value, including false. That default is a domain decision requiring approval and tests, not a general truth about all older records.
Keep wire versions at the boundary rather than making every internal caller understand every historical shape. Document the supported version window and how long stored messages may remain readable. A version number is not proof that the rest of the object is valid. The decoder must inspect the actual version-specific fields before normalization. Unknown versions require an explicit rejection or quarantine path rather than being treated as the newest version.
Validate unknown data before normalization
JSON.parse can produce a value of any shape at runtime. Start from unknown, check for a non-null object, validate the version tag, then check the fields required by that version. Version 1 requires a string name; version 2 requires a string displayName and a Boolean active. Check false as a Boolean value rather than using truthiness. Decide how arrays, inherited fields, unknown keys, and empty text are handled in the actual contract.
Only after the decoder establishes the required facts should it construct a typed V1 or V2 and pass that value to normalize. A type assertion on JSON.parse output does not execute validation, convert a field, or reject a future version. Return a documented error or quarantine outcome when the boundary fails. Use safe diagnostics such as version and failure category rather than logging a complete private profile.
Map supported variants deliberately
A discriminated union connects each literal version tag to its fields. A switch on version narrows the input so the version 1 branch reads name and the version 2 branch reads displayName and active. The normalizer returns a new Profile with the stable internal shape. Preserve meaningful false from version 2; an OR fallback would replace false and change its meaning. A nullish or explicit presence policy should still be chosen from the domain contract rather than applied indiscriminately.
When adding a new wire version, document field renames, defaults, and behavior for missing data. A never-based exhaustive check can make the compiler flag a new union variant that lacks a branch. That static check covers known source variants; it cannot reject an arbitrary network object that never passed through the decoder. Test both the new valid branch and the unknown-version runtime path.
Plan compatibility and rollback
A versioned contract is an operational agreement among producers, consumers, and stored data. During a staged rollout, old and new readers and producers may overlap, and queued or stored messages can outlive a deployment. Decide which versions each reader supports, when a producer may emit a new version, and what happens when an older reader encounters it. Test forward and rollback scenarios before removing an adapter.
A rollback may restore an older reader while version 2 records already exist. The rollback plan must address those records rather than assuming deployments erase data. Use isolated fixtures to verify the supported combinations and quarantine or rejection behavior. Track migration progress and approval of any default, but avoid claiming a universal rollout order: the right sequence depends on the actual service and compatibility policy.
Verify semantic equivalence and failures
Create independent fixtures for a version 1 record, a version 2 record with active false, missing fields, wrong field types, null, and an unsupported version. Assert exact normalized fields and verify invalid data never reaches the normalizer. Equivalent names across versions can map to the same internal displayName, but their active values depend on the explicit policy; do not erase false for the sake of superficial equivalence.
Compile type examples in fresh isolated TypeScript 5.7.3 builds with strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes, and noEmitOnError. Check intended diagnostics and absence of new output for negative source, then run valid artifacts in Node 22.23.3. Synthetic examples and rollout traces do not prove a production migration or rollback; actual producers, storage, authorization, and deployment need separate evidence.
20 worked examples
1. Normalize version one
Problem: Map a version 1 name into the internal profile with its stated default.
- The version 1 policy maps name and supplies active true.
- The resulting profile contains Ada and the explicitly chosen migration default.
type V1 = { version: 1; name: string }; type Profile = { displayName: string; active: boolean };
function normalize(x: V1): Profile { return { displayName: x.name, active: true }; }
console.log(JSON.stringify(normalize({ version: 1, name: "Ada" })));
{"displayName":"Ada","active":true}
Why this result follows: The resulting profile contains Ada and the explicitly chosen migration default.
2. Preserve version two false
Problem: Normalize a version 2 profile without replacing its false active field.
- The version 2 input explicitly supplies Boolean false.
- The normalizer copies false rather than replacing a meaningful value with a default.
type V2 = { version: 2; displayName: string; active: boolean };
function normalize(x: V2) { return { displayName: x.displayName, active: x.active }; }
console.log(JSON.stringify(normalize({ version: 2, displayName: "Ada", active: false })));
{"displayName":"Ada","active":false}
Why this result follows: The normalizer copies false rather than replacing a meaningful value with a default.
3. Compare version policies
Problem: Compare internal active values from old and new representations.
- The old variant uses the policy default and the new variant supplies false.
- The same display name does not erase the distinct source of each active value.
type V1 = { version: 1; name: string }; type V2 = { version: 2; displayName: string; active: boolean };
function normalize(x: V1 | V2) { return x.version === 1 ? { displayName: x.name, active: true } : { displayName: x.displayName, active: x.active }; }
console.log(normalize({ version: 1, name: "Ada" }).active, normalize({ version: 2, displayName: "Ada", active: false }).active);
true false
Why this result follows: The same display name does not erase the distinct source of each active value.
4. Reject unknown source variant
Problem: Reject a typed version 3 object outside the supported union.
- The declared union includes only literal versions one and two.
- The checker rejects version three in checked source before fresh emission.
type Wire = { version: 1; name: string } | { version: 2; displayName: string; active: boolean };
const x: Wire = { version: 3, name: "Ada" };
console.log(x);
TS2322
Why this result follows: The checker rejects version three in checked source before fresh emission.
5. Reject null input
Problem: Reject null before examining a version property at runtime.
- Null fails the explicit non-null object condition.
- The boundary can reject it before attempting a property read.
const input: unknown = null;
console.log(typeof input === "object" && input !== null ? "object" : "invalid");
invalid
Why this result follows: The boundary can reject it before attempting a property read.
6. Reject missing version
Problem: Reject an object without the required version tag.
- The synthetic object has no version property.
- The boundary cannot select a supported decoder without the required tag.
const input: unknown = { name: "Ada" };
console.log(typeof input === "object" && input !== null && "version" in input);
false
Why this result follows: The boundary cannot select a supported decoder without the required tag.
7. Reject unknown version
Problem: Reject a runtime version tag outside the supported values one and two.
- The actual tag is three, not either supported version.
- The runtime policy rejects or quarantines it instead of guessing a decoder.
const version: unknown = 3;
console.log(version === 1 || version === 2 ? "supported" : "unsupported");
unsupported
Why this result follows: The runtime policy rejects or quarantines it instead of guessing a decoder.
8. Version one field type
Problem: Validate a version 1 name field as text before normalization.
- The object has the supported tag and a string name.
- The version-specific runtime checks accept this synthetic control.
const input: unknown = { version: 1, name: "Ada" };
const ok = typeof input === "object" && input !== null && "version" in input && input.version === 1 && "name" in input && typeof input.name === "string";
console.log(ok);
true
Why this result follows: The version-specific runtime checks accept this synthetic control.
9. Version one wrong field
Problem: Reject a numeric name in a version 1 record.
- The tag is supported but name is a number.
- The field-type check rejects the record before normalization.
const input: unknown = { version: 1, name: 7 };
const ok = typeof input === "object" && input !== null && "version" in input && input.version === 1 && "name" in input && typeof input.name === "string";
console.log(ok);
false
Why this result follows: The field-type check rejects the record before normalization.
10. Version two false valid
Problem: Validate false as a Boolean active field in version two.
- The active value is Boolean false, not a missing field.
- The explicit Boolean check accepts the meaningful false value.
const input: unknown = { version: 2, displayName: "Ada", active: false };
const ok = typeof input === "object" && input !== null && "version" in input && input.version === 2 && "displayName" in input && typeof input.displayName === "string" && "active" in input && typeof input.active === "boolean";
console.log(ok);
true
Why this result follows: The explicit Boolean check accepts the meaningful false value.
11. Version two wrong active
Problem: Reject a string active field in a version 2 record.
- The active property is text, not a Boolean.
- The version-specific field check rejects the misleading string representation.
const input: unknown = { version: 2, displayName: "Ada", active: "false" };
const ok = typeof input === "object" && input !== null && "version" in input && input.version === 2 && "displayName" in input && typeof input.displayName === "string" && "active" in input && typeof input.active === "boolean";
console.log(ok);
false
Why this result follows: The version-specific field check rejects the misleading string representation.
12. Missing active field
Problem: Reject a version 2 object that omits its required active field.
- The version 2 fixture does not contain active.
- The required-field check fails before the normalizer receives a typed V2.
const input: unknown = { version: 2, displayName: "Ada" };
console.log(typeof input === "object" && input !== null && "active" in input);
false
Why this result follows: The required-field check fails before the normalizer receives a typed V2.
13. Truthiness loses false
Problem: Observe a Boolean fallback that incorrectly replaces false.
- False is falsy, so OR selects its right operand.
- This fallback changes the supplied false and violates the version 2 policy.
const active: boolean = false;
console.log(active || true);
true
Why this result follows: This fallback changes the supplied false and violates the version 2 policy.
14. Nullish keeps false
Problem: Preserve false when a nullish fallback is applied.
- False is present and is not null or undefined.
- Nullish coalescing preserves the meaningful Boolean false in this fixture.
function read(active?: boolean): boolean { return active ?? true; }
console.log(read(false));
false
Why this result follows: Nullish coalescing preserves the meaningful Boolean false in this fixture.
15. Narrow tagged union
Problem: Read a version-specific field only after testing its tag.
- The version two tag narrows the union to the second shape.
- The selected branch reads displayName and returns the supplied text.
type Wire = { version: 1; name: string } | { version: 2; displayName: string; active: boolean };
function nameOf(x: Wire): string { return x.version === 1 ? x.name : x.displayName; }
console.log(nameOf({ version: 2, displayName: "Ada", active: false }));
Ada
Why this result follows: The selected branch reads displayName and returns the supplied text.
16. Reject unguarded field
Problem: Reject reading a version-one field from an unguarded union.
- The version two alternative does not declare name.
- The checker requires narrowing before accessing the version-one field.
type Wire = { version: 1; name: string } | { version: 2; displayName: string; active: boolean };
function nameOf(x: Wire): string { return x.name; }
TS2339
Why this result follows: The checker requires narrowing before accessing the version-one field.
17. Exhaustive new version
Problem: Handle a newly declared version three in an exhaustive switch.
- The switch explicitly handles both declared tags.
- The version three branch returns Ada while retaining the exhaustive check.
type Wire = { version: 1; name: string } | { version: 3; displayName: string };
function never(x: never): never { throw new Error(String(x)); }
function nameOf(x: Wire): string { switch (x.version) { case 1: return x.name; case 3: return x.displayName; default: return never(x); } }
console.log(nameOf({ version: 3, displayName: "Ada" }));
Ada
Why this result follows: The version three branch returns Ada while retaining the exhaustive check.
18. Missing new version branch
Problem: Reject an exhaustive switch that omits its declared version three.
- The default branch still contains the unhandled version three.
- The remaining variant cannot be passed to never, forcing source review.
type Wire = { version: 1; name: string } | { version: 3; displayName: string };
function never(x: never): never { throw new Error(String(x)); }
function nameOf(x: Wire): string { switch (x.version) { case 1: return x.name; default: return never(x); } }
TS2345
Why this result follows: The remaining variant cannot be passed to never, forcing source review.
19. Parse is not validate
Problem: Show that syntactically valid JSON can contain an unsupported version.
- JSON parsing accepts the synthetic object syntax.
- The parsed version still needs a separate supported-version decision.
const parsed: unknown = JSON.parse('{"version":3}');
console.log(typeof parsed === "object" && parsed !== null && "version" in parsed && parsed.version === 3);
true
Why this result follows: The parsed version still needs a separate supported-version decision.
20. Select internal fields
Problem: Construct an internal profile without copying an extra wire field.
- The new object explicitly selects the two internal fields.
- The extra source field is not copied into this normalized output.
const input = { version: 2 as const, displayName: "Ada", active: false, extra: "synthetic" };
const output = { displayName: input.displayName, active: input.active };
console.log(JSON.stringify(output));
{"displayName":"Ada","active":false}
Why this result follows: The extra source field is not copied into this normalized output.
Common errors and fixes
An unknown version is treated as a known one
- Why it happens
- The boundary assumes every incoming tag matches a declared union member.
- How to fix it
- Validate the tag and reject or quarantine unsupported versions.
- Prevent it next time
- Test a future version and monitor rejected version counts.
A false value changes to true
- Why it happens
- A truthiness fallback replaced a valid Boolean false.
- How to fix it
- Use the validated Boolean directly or apply an explicit absence rule.
- Prevent it next time
- Include false in migration fixtures and assert the normalized value.
Old stored records fail after rollout
- Why it happens
- The new consumer removed support before old records expired or migrated.
- How to fix it
- Restore a compatible adapter or perform a verified migration.
- Prevent it next time
- Plan the compatibility window, rollback, and retained-message lifetime.
20 practice exercises
1. What is active for a version 1 record?
Show hint
The old representation lacks active, so the example applies a documented migration policy.
Show worked solution
It is true under the exampleโs explicit migration policy. That default should be approved by the domain owner and tested; it is not a general rule about versioned profiles.
For a version 1 record, active is true under this example policy. The default must be approved by the domain owner and tested; it is not a general rule about old profiles. A version 2 record retains its supplied Boolean, including false.
Check your solution
- Version 1 receives active true under the stated policy.
- Version 2 false remains false.
2. Can normalize safely accept JSON.parse output via an assertion?
Show hint
An assertion is not an executable decoder for parsed JSON.
Show worked solution
An assertion does not validate the parsed value. Check its object shape, supported version, and version-specific fields first; only then construct the typed variant and normalize it. Unknown versions need an explicit rejection or quarantine path.
Treat JSON.parse output as unknown and validate a non-null object, supported version, and all fields required by that version before constructing a typed variant and calling normalize. Reject or quarantine unsupported versions explicitly. Test malformed and valid controls at the boundary.
Check your solution
- Unsupported versions do not enter normalize.
- Version-specific fields are checked at runtime.
3. Normalize version 1 {version: 1, name: "Ada"} using the stated active policy.
Show hint
Version one maps name to displayName and defaults active to true.
Show worked solution
The normalized Profile is {displayName: "Ada", active: true}. The true value is an explicit example migration policy, not a universal rule. Obtain domain approval and test the default before applying it to real stored profiles.
Check your solution
- The display name is Ada
- The documented version-one default is true
4. Normalize version 2 with displayName "Ada" and active false.
Show hint
Preserve the supplied Boolean even though it is falsy.
Show worked solution
The normalized Profile is {displayName: "Ada", active: false}. Do not use active || true, which would replace false. Validate that active is actually Boolean before constructing the typed version-two variant from unknown data.
Check your solution
- The active value remains false
- The display name is Ada
5. Explain why JSON.parse output cannot safely enter normalize through an assertion alone.
Show hint
An assertion does not inspect the parsed runtime value.
Show worked solution
Treat the parsed value as unknown, check a non-null object, supported version, and all version-specific fields before constructing a typed variant. Reject or quarantine unknown versions according to policy. An assertion performs none of those checks or conversions.
Check your solution
- The runtime shape is validated
- Unsupported versions follow an explicit path
6. Reject null before reading a version field from external data.
Show hint
Check for a non-null object at the boundary.
Show worked solution
Reject null as invalid input before any property read. Then inspect version only for a suitable object, with array and own-property handling defined by the contract. Include a valid object control to demonstrate the accepted path.
Check your solution
- Null is rejected without property access
- A valid control reaches version checking
7. Reject a version 1 record whose name is numeric 7.
Show hint
The version tag does not validate its required fields.
Show worked solution
Even with version: 1, {name: 7} violates the required string field. Return the documented validation failure before normalize is called. Test {version: 1, name: "Ada"} as a valid control and inspect the exact normalized fields.
Check your solution
- The numeric name is rejected
- The valid version-one control normalizes
8. Reject version 2 when active is missing or the string "false".
Show hint
The required field must be an actual Boolean.
Show worked solution
Both fixtures fail the version-two contract: one lacks active and the other supplies a string. Accept actual Boolean false as a valid control. Check presence and type explicitly rather than relying on truthiness or coercion.
Check your solution
- Missing and string active values are rejected
- Boolean false is accepted
9. Explain why version 3 must not be silently treated as version 2.
Show hint
An unknown representation may have different required semantics.
Show worked solution
Reject or quarantine version 3 according to the documented operational policy until its fields and mapping are supported. Treating it as version 2 can misinterpret data. Record a safe version identifier and failure category rather than logging an entire private profile.
Check your solution
- Version 3 follows an explicit unsupported path
- No guessed version-two normalization occurs
10. Explain why active || true violates the version-two false policy.
Show hint
False is a meaningful Boolean but is falsy.
Show worked solution
When active is false, || selects true and silently changes the supplied meaning. Validate active as Boolean and copy it directly for version 2. Test false separately from missing data so a fallback cannot erase it.
Check your solution
- Version-two false remains false
- A missing active field is rejected
11. Define the responsibilities of a decoder and a normalizer for V1 and V2.
Show hint
The decoder handles unknown input; the normalizer maps a validated variant.
Show worked solution
The decoder checks object shape, supported version, and version-specific fields, then constructs V1 or V2. The normalizer maps that typed variant to Profile using the approved policy. Test invalid boundary inputs separately from the pure normalization of valid variants.
Check your solution
- Invalid input stops at the decoder
- Valid variants map to the internal shape
12. Add version 3 to a discriminated union with an exhaustive never check.
Show hint
A new known variant requires an explicit normalizer branch.
Show worked solution
Add the documented V3 shape and a switch case that maps its fields to Profile. Keep assertNever in the default branch so an omitted variant causes a diagnostic. Test the valid V3 mapping and keep a separate runtime rejection for unknown versions.
Check your solution
- The V3 branch is explicit
- Unknown runtime versions are still rejected
13. Explain why a never check does not validate a network message at runtime.
Show hint
The exhaustive check covers the declared source union.
Show worked solution
A never check helps detect an unhandled known variant during compilation, but an arbitrary network object can contain an unsupported version or wrong fields. Validate unknown input at runtime before normalizing. Test both static exhaustiveness and malformed external fixtures.
Check your solution
- Known union branches are checked statically
- Unknown external data is validated at runtime
14. Test that an invalid version-two record never reaches a synthetic normalizer.
Show hint
Use a recording fake to observe normalizer calls.
Show worked solution
Pass {version: 2, displayName: "Ada", active: "false"} to the decoder, assert a type failure, and assert the normalizer fake has zero calls. Then pass a valid Boolean false control and verify the expected internal profile.
Check your solution
- The invalid record is rejected before normalization
- The valid false control normalizes
15. Compare a V1 Ada profile with a V2 Ada profile whose active field is false.
Show hint
The common name maps alike but active follows different sources.
Show worked solution
Both normalize to displayName "Ada". Under the stated policy, V1 has active true by default while V2 preserves its supplied false. Assert both fields for both records rather than assuming identical names imply identical complete profiles.
Check your solution
- Both display names are Ada
- V1 active is true and V2 active is false
16. Plan a staged rollout in which readers support V1 and V2 before V2 producers deploy.
Show hint
Test the actual producer-reader compatibility window.
Show worked solution
Verify new readers accept both supported fixtures, keep old producer behavior during the transition, then enable V2 production according to the service policy. Test stored messages and rollback. The exact deployment order is application-specific and must be approved operationally.
Check your solution
- New readers accept V1 and V2
- Stored messages and rollback are tested
17. Explain the rollback risk when V2 records remain after restoring a V1-only reader.
Show hint
Stored data can outlive the deployment that produced it.
Show worked solution
A V1-only reader may reject or misinterpret already stored V2 records. The rollback plan must define a compatible reader, conversion, quarantine, or other documented handling before reverting. Test the actual stored-message scenario in an isolated environment.
Check your solution
- Existing V2 data is accounted for
- Rollback behavior is tested
18. Choose safe diagnostics for an unsupported version without logging a private profile.
Show hint
Record the version identifier and a failure category.
Show worked solution
Record a safe version identifier and documented failure category at the appropriate diagnostic boundary, not the complete profile or secrets. Return a safe failure or quarantine outcome according to policy. Test that the diagnostic omits private fields.
Check your solution
- The version and category are recorded safely
- Private profile fields are omitted
19. Design a test matrix for supported and malformed profile versions.
Show hint
Include each valid version, false, missing fields, wrong types, and unknown tags.
Show worked solution
Assert V1 Ada maps to active true under the approved policy and V2 Ada with false preserves false. Reject null, missing required fields, wrong types, and version 3. Verify invalid inputs never reach normalize and record exact categories if promised.
Check your solution
- Both supported variants produce expected profiles
- Malformed and unknown variants are rejected
20. Explain what a passing synthetic migration fixture does not prove about production rollout.
Show hint
Limit the conclusion to the modeled data and environment.
Show worked solution
A local fixture supports its specified decoding and normalization cases, but it does not prove actual producers, stored messages, permissions, or rollback procedures are compatible. Test the real integration in an authorized environment, record the supported-version window, and monitor rollout according to policy.
Check your solution
- The synthetic cases are verified
- Production rollout and rollback need separate evidence
Key takeaways
- Normalize supported external versions into a stable internal contract.
- Validate raw values and test semantic defaults and rollout compatibility.
- The V1 active default is a domain policy, not a universal rule.
- A TypeScript assertion does not validate parsed JSON.
- Stored versioned data can outlive a deployment and affect rollback.