Hoi hoi! π
I'm @nyaomaru, a frontend engineer just back from a short vacation on Texel, a small island in the Netherlands. πΈποΈ
Today, let's talk ...
For further actions, you may consider blocking this person and/or reporting abuse
This is a good example of a gap between TypeScript's static types and runtime validation.
What stood out to me is that a type predicate can be completely valid to the compiler while the implementation doesn't actually verify the whole type. That's where the silent drift becomes dangerous: you can update the
Usertype and still have a guard that is effectively checking an older version of the contract.I like the
typedStruct<User>()approach because it makes that relationship explicit and gives the compiler something concrete to check when the type and guard get out of sync.It doesn't remove the need to maintain the runtime validation, but it makes forgetting to update it much harder to miss. That feels like the real win here.
Thanks for the thoughtful comment! πΈ
Yeah, that silent drift is exactly what made me want to write this article
Itβs scary how easy it is for the type and runtime contract to quietly fall out of sync.
And Iβm glad you liked the
typedStructapproach! I think it can be useful in a lot of places where an existing TypeScript type should stay aligned with a runtime guard, so Iβd be happy if you give it a try. πExactly. I think the real value is not just the helper itself, but making the relationship between the type and the runtime contract visible. Once the same shape is maintained in two independent places, drift becomes a maintenance problem that depends on someone remembering to update both.
Making that dependency visible to the compiler changes the failure mode: instead of silently forgetting a field, you get a signal while developing. Thatβs a small change, but it can save a surprisingly painful debugging session later. πΈ
Exactly! Thatβs the part I wanted to emphasize too. πΈ
The helper itself is small, but making the dependency visible to the compiler changes the failure mode from βsomeone forgotβ to βthe code no longer compiles.β
Thanks for putting it so clearly! π
The core problem is that
value is Useris a promise the compiler accepts and cannot check. Worth adding which direction of drift hurts more.A stale guard returning
falsetoo often is loud: a rejection, a bug report, fixed that afternoon. A stale guard returningtruetoo often, which is exactly yourroleexample, is silent. The malformed object crosses the boundary and fails much deeper, usually inside a function that never claimed to validate anything. The cost isn't the bug, it's the distance between symptom and cause.Which is why I've settled on reversing the dependency rather than testing it: derive the type from the validator, not the validator from the type. If
Useris inferred fromuserSchema, addingroleupdates the type automatically, and drift stops being something you can forget and becomes something you can't express. Tests that check a guard against its type are good, and they're still catching a mistake a different shape would have prevented.The one place I'd keep hand-written guards is where the runtime shape genuinely isn't the type, like a legacy API where three fields mean the same thing.
I agree with that overall. π±
If the validator can be the source of truth, a schema-first approach is probably the strongest way to prevent drift structurally. In that kind of code, deriving the TypeScript type from something like a
Zodschema makes a lot of sense.Where I think type guards become useful is when the type already comes from somewhere else.
For example,
OpenAPI-generated types orbrowser/nativeAPIs already have an external source of truth. Re-declaring those shapes again as schemas can introduce a second contract to maintain, which creates its own kind of drift.Thatβs where I like the type-guard approach.
Itβs lightweight, works well with existing types and native predicates, and can be added only where runtime narrowing is actually needed.
So for me itβs less βschema vs type guardsβ and more about choosing the right source of truth for each boundary.
And I really like your point about false positives being more dangerous because they increase the distance between the cause and the eventual failure. Thatβs a great way to frame the cost of silent drift.
I actually wrote about this distinction before in a comparison between
is-kitandZod, including where I think schema-first and type-guard-first approaches fit differently. If you're interested, feel free to take a look! πΈdev.to/nyaomaru/is-kit-vs-zod-a-pr...
That distinction is the better framing and I'll take it: the rule isn't schema-first, it's one source of truth per boundary. Two contracts describing the same shape is the disease. A schema is just one of the cures.
Where I'd push back a little is the OpenAPI case, because I think it proves the principle rather than the exception. The generated type is already a derived artifact; the spec is the origin. If you then hand-write a guard against that generated type, you have re-created the second contract you were trying to avoid. It just lives in a different file and drifts on a different schedule. Generating the validator from the same spec keeps the origin count at one.
The case I can't argue with is browser and native shapes. There is no upstream document to generate from, so a hand-written predicate is the only honest option.
One habit that has helped me there, and it follows directly from your false-positive point: type the predicate to what you actually checked. A guard that verifies two of fourteen fields and claims
value is Useris lying by exactly twelve fields. If it returnsvalue is Pick<User, 'id' | 'role'>, the narrowing is true, and the compiler stops you at the first place that needs more than you proved. Smaller promise, but one you can keep.Reading the is-kit and Zod comparison next. Curious whether is-kit does anything about exhaustiveness, since that is the part a hand-written guard can never check about itself.
Thatβs a really good distinction πΈ
I agree that βone source of truth per boundaryβ is the better framing.
And youβre right about OpenAPI too. The generated TypeScript type is already a derived artifact, so if the spec is available, generating both the type and the runtime validator from that same origin is cleaner than hand-writing a second contract against the generated type.
I also really like your point about typing a predicate to exactly what it checked. Returning
Pick<User, 'id' | 'role'>instead ofUseris a much smaller promise, but also a much more honest one.On the exhaustiveness point: thatβs a good catch.
typedStructcan keep a single branch aligned, butoneOf(...)does not currently prove that every member of a union is covered.I opened an issue for that and plan to explore it further π
issue
Thanks for the thoughtful feedback π
This gave me a few good design questions to think about. πΈ
Glad it landed. Good luck with the exhaustiveness issue β that's a genuinely hard property to get a type checker to prove for you rather than just hoping the next branch addition remembers to update the union too.
Yeah, I think discriminated unions give me a good path to make the branch coverage exhaustive at compile time. Iβll keep working on it πΈ
Hit this exact bug in production last year β added an
emailfield to a type, forgot the guard, and spent 4 hours wondering why downstream code was crashing onundefined. The fix I landed on was generating guards from the type itself usingzodschemas, so the runtime check and the type literally can't drift apart. Hand-written guards are fine for 2-field types but once you're past 5 or 6 fields, you're just betting you'll remember to update two places every time. The compiler should be doing this for you.Yeah, this is exactly the kind of bug that can easily make it all the way to production πΈ
Zodis definitely a good solution when you already need a runtime schema, but I donβt think creating schemas for every internal type is always ideal. It can blur the boundary between plain TypeScript types and runtime validation, and it also adds another layer to maintain.Thatβs one of the reasons I like using type guards with helpers such as
typedStruct. You can reduce unnecessary schema declarations while keeping the type itself as a normal TypeScript type, and still make structural drift visible to the compiler.Definitely give it a try
is-kit! πΈGreat article. I think this is one of those TypeScript pitfalls that many developers know exists but rarely stop to think about. The compiler happily trusts a custom type predicate, so it's surprisingly easy for runtime validation to fall out of sync with the actual type definition as the codebase evolves. The examples made the risk very clear, and I like the idea of making structural drift visible at compile time instead of discovering it through bugs later. Thanks for highlighting a subtle but important issue. π
Thanks! πΈ Iβm glad it helped make the issue a little clearer!
I was pretty shocked to learn this, but I just tested
The compiler is perfectly capable of rejecting isFoo for not actually checking for Foo-ness, so this is sad.
I recommend using zod and ts-pattern to address this.
Yeah, that behavior surprises a lot of people the first time they see it. And me too!πΈ
One small nuance though: once you explicitly write
y is Foo, TypeScript treats that predicate as a contract. It generally doesnβt prove that the function body actually establishesFoo, so evenreturn trueis accepted.And yes, a schema-first approach with something like Zod is a strong way to avoid this class of drift entirely when the schema can be the source of truth.
ts-patternis great too, although I see it more as a pattern-matching / exhaustiveness tool than a replacement for runtime validation.For cases where the TypeScript type already exists, I like
typedStruct<Foo>()because it keeps the type as the source of truth while making the guard definition structurally checkable.This is one of those TypeScript gotchas thatβs easy to miss until it causes a really confusing bug π .
I really liked the point that a type predicate is essentially a promise, not a proof. The idea of making the guard structurally depend on the existing type is a nice way to turn βI hope I remembered to update the guardβ into something the compiler can actually help catch.
Also appreciated the explanation of optional vs nullable propertiesβthat distinction trips people up more often than it should. Great practical write-up! π
Thank you so much! πΈ
Yeah, βa promise, not a proofβ was really the core idea I wanted to communicate.
And Iβm glad the
optional vs nullablepart stood out too, those two often look similar at first, but they represent different runtime contracts.Really appreciate the thoughtful feedback! π
The promise-not-proof framing is exactly right, and I would extend it one step: in agent-heavy codebases the drift is not just a maintenance problem, it becomes a security property. A guard that validates an older shape of the type is an implicit allowlist that never updates. Whatever the agent or integration passes through it gets narrowed to a contract the author last reviewed months ago.
The boundary-only discipline from the discussion here is the practical middle ground. Guards at the trust perimeter where unknown enters, and the compiler owns everything inside. The failure mode I have actually seen in production is your second category: the stale guard that returns true too often. It fails three layers downstream from the real decision, and by then the call stack reads like fiction.
typedStruct closing that loop at compile time is a small change with a big consequence: the review conversation moves from hoping the guard matches to reading what the compiler already proved.
Thank you for the insightful comment! πΈ
I completely agree.
In the AI era, agents often treat the current codebase as the source of truth. If type drift already exists, they may simply build on top of that mismatch without anyone noticing until it fails in production.
That is exactly where
typedStructhelps. It prevents silent drift and unintended runtime failures by making the compiler verify that the guard still matches the type.And as you said, keeping runtime validation at clear trust boundaries improves not only readability, but also long-term maintainability. πΈ
I'd test extra keys next. Does
typedStruct<User>()reject runtime objects with fields outside the declared map, or only validate the fields it knows about?Thanks for the comment! πΈ
By default,
typedStruct<User>()validates the fields it knows about, so extra runtime fields are allowed. If you want to reject extra own enumerable string keys too, you can enableexact: true.The main purpose of
typedStructis a little different from a schema validator, though itβs meant to help you build a type guard that stays type-safe and synchronized with an existing TypeScript type.So compile-time guard shape and runtime exactness are separate choices. πΈ
One angle I'd add: the drift problem only really matters at trust boundaries β API payloads, localStorage, postMessage. Guards on purely internal values just double the maintenance bill for bugs that can't actually happen. I've started treating isUser-style checks as boundary contracts and letting the type system own everything inside, which makes each guard feel a lot more worth its upkeep.
I agree that βboundary contractsβ is a really good way to frame it. πΈ
In production projects, I also prefer to introduce runtime guards at clear boundaries rather than scattering them throughout the codebase. If a value is purely internal and the type system can guarantee it end-to-end, adding another runtime check usually doesnβt buy much.
That said, I think there are more boundaries than just API payloads.
The important question is often
JSON.parse, DOM/browser APIs,postMessage, storage, third-party data, and similar places can all create those boundaries.So I see type guards mainly as a way to establish trust at those points, then let TypeScript own the values once theyβre safely inside. πΈ
The "promise, not a proof" framing is the right way to put it, and typedStruct closing the gap between "the field map compiles" and "the field map actually matches the type" is a real improvement over hand-rolled guards drifting silently.
One case I'm curious how it handles: discriminated unions, where the shape of the other fields depends on a tag field rather than each field being independently checkable. Something like
type Event =
| { kind: "click"; x: number; y: number }
| { kind: "scroll"; delta: number };
A per-field struct naturally wants one flat map of key to guard, but here the valid keys and their types change depending on kind. Do you compose separate typedStruct calls per branch and pick one with oneOf/or based on the discriminant, or is there a more direct way is-kit expects you to model that? That's usually where I've seen hand-written guards diverge from the type fastest in practice, since it's easy to validate kind correctly and then forget that x/y only make sense in the click branch.
Great question! πΈ
For a discriminated union like that, Iβd model each branch separately with
typedStruct, then compose them withoneOf.For example π
That way, each discriminant stays coupled to the fields that belong to that branch.
So if the
clickvariant later gains another required field and its guard isnβt updated,typedStruct<ClickEvent>()catches that drift at compile time.I prefer this over flattening the whole union into one field map, because the branch structure remains explicit in both the TypeScript type and the runtime guards. πΈ
the silent drift problem hits harder when the type grows organically over time. I've seen this fail specifically on discriminated unions where the guard was written for the initial two variants and silently accepts a third variant added six months later that the author forgot to update the runtime check for. the only thing that caught it was a test that round tripped through a serialization boundary, not the type system. worth asking whether the validation library approach fully escapes this or just defers the same problem to the schema definition?
Exactly, a validation library alone doesnβt automatically solve drift. If the schema and TypeScript type are maintained independently, it can just move the same problem somewhere else. π±
That exact discriminated-union case is one reason I added
discriminatedUnionin is-kit v1.15:If a third variant is later added to
Result, this definition stops compiling until that discriminant and its guard are added too.So the goal isnβt just βuse a validation libraryβ.
itβs to make the runtime schema depend on the TypeScript contract strongly enough that they fail together.
v1.15 release:
v1.15 πΈ