5 ms·
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 a
by mhermher 4y 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.
- madeofpalk 4y agoYou 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 https://github.com/microsoft/TypeScript/pull/50666
- mhermher 4y agoyeah. 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!)
- davidzweig 4y agoWe do it like this: https://imgur.com/a/AdeRncw 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.