Re:Show HN: Ezno, a type checker for JavaScript and optimise...
by madeofpalk on Friday September 23, 2022 @03:13PM
(#32955885)
You can't actually narrow `unknown` down to a structure yet, as you have no way to test whether `property in unknown` or not.
Well, until this is released! https://github.com/microsoft/TypeScript/pull/50666
Re:Show HN: Ezno, a type checker for JavaScript and optimise...
by mhermher on Friday September 23, 2022 @04:39PM
(#32956790)
yeah. You have to assert an object (`Record<string, unknown>`) type first within your asserter (or array or whatever). We ended up having whole stacks of re-usable assertion functions to be used at these boundaries (re-usable on server side too if you're using node!)
Re:Show HN: Ezno, a type checker for JavaScript and optimise...
by davidzweig on Friday September 23, 2022 @06:53PM
(#32958021)
We do it like this:
https://imgur.com/a/AdeRncw
Just a simple function (ensureType) that checks primitive types (angle brackets for min length). You reconstruct the object using ensureType, writing it back into itself. EnsureType returns what is passed in, with the corresponding type. Has worked well.
But the solution really is to assume `: unknown` at API boundaries and run the values through assertion functions: `isSomeType(x: unknown): asserts x is SomeType`.
After using this sort of pattern, I don't think I would want automatic runtime checks anymore, because creating your own explicitly and calling it explicitly works out not so bad.