3 ms·
Hmm, I was reading the doc[1], and it seems like type guards aren't run-time checks though; they're a way to write a function that checks a given type and then
by winter_blue 4y ago
Hmm, I was reading the doc[1], and it seems like type guards aren't run-time checks though; they're a way to write a function that checks a given type and then narrows that type to another more specific type.
I think what OP might've meant by run-time checks is auto-generating code that wraps every unpredictable/non-guaranteed boundary with a run-time type check. So if you have some data with the "any" type data being turned into a type or a use of the "as" keyword (e.g. `someType as anotherType`), then add a run-time check that throws an error at that boundary (instead of the code erroring out elsewhere, or resulting in incorrect behavior). Something like
[1] https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards https://www.typescriptlang.org/docs/handbook/advanced-types....
- eyelidlessness 4y ago> Hmm, I was reading the doc[1], and it seems like type guards aren't run-time checks though; they're a way to write a function that checks a given type and then narrows that type to another more specific type. That’s a runtime type check! Any equivalent you might bake into TypeScript would do the exact same thing, but it would do it rigidly in ways people don’t expect (being strict about input types, ie “do what I say not what I mean) or rigidly in ways people don’t expect (“do what I mean as long as you mean exactly what we allow”). Again, fine grained type guards as implemented by zod/io-ts/etc solve this problem and either give you all you need already or demonstrate exactly how you can use existing language features to achieve exactly what OP and anyone else asking for runtime types wants.
- mcluck 4y agoI agree and I'd like to add that if someone wants to throw an error for invalid type casts, they can use assertion functions. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions https://www.typescriptlang.org/docs/handbook/release-notes/t...
- eyelidlessness 4y agoThat’s an option I considered mentioning, but it has some weird ergonomics that many people won’t like.