Hacker News new | ask | show | jobs
by mhermher 1362 days ago
I really wanted this in my earlier usage of typescript as 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.

2 comments

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

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!)
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.