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
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 😸
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! 👍
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!
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 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! 👏
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. 😸
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. 😸
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 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 😸
Type guard drift là một trong những bug class khó bắt nhất vì nó lọt qua cả compile-time lẫn test suite thông thường. Mình từng gặp case schema validation (zod) được update nhưng type guard thủ công quên không sync — production mới phát hiện khi user gửi payload mới mà guard vẫn
return true.Một pattern giúp giảm rủi ro: derive type guard từ schema thay vì viết tay. Với zod/vine/arktype, dùng
schema.safeParserồi narrow type quadataproperty — guard và type luôn đồng bộ vì cùng nguồn. Nếu buộc phải viết custom guard (ví dụ performance-critical path), để nó bên cạnh schema definition trong cùng file, thêm comment// sync with UserSchema v3để reviewer dễ catch khi PR thay đổi schema.Còn một điểm article chưa nhắc: exhaustiveness check trên discriminated union. TypeScript sẽ báo lỗi khi thiếu case, nhưng type guard hand-rolled thường quên update switch — dẫn đến
neverbranch im lặng. DùngassertNeverhoặcsatisfiesđể ép compiler nhắc nhở PS: the tool I meant is on labagent .techVấn đề type guard bị lệch so với interface thực tế là một cái bẫy cực kỳ khó chịu khi dự án lớn dần. Mình từng gặp trường hợp thêm một field optional vào interface nhưng quên cập nhật logic kiểm tra trong type guard, dẫn đến việc runtime vẫn chạy nhưng TypeScript lại báo lỗi logic hoặc ngược lại. Cách tốt nhất để tránh việc này là luôn sử dụng các thư viện schema validation như Zod để tự động hóa việc tạo type từ runtime validation. Việc duy trì hai nguồn sự thật riêng biệt cho cả type và logic kiểm tra thường chỉ làm tăng thêm technical debt và sai số mà thôi (site: labagent .tech)