by RyanCavanaugh · 3y ago · 0 comments
There are dozens of questions you can throw at this code: What if the input's a union? What if it's a nested union -- how do you avoid combinatorial explosion? What if the input is a function -- how do you validate its parameter types using runtime information? What if the input is a conditional type? What if you're inside a generic function? The list is enormous and it quickly gets into "you've dug too deep and unleashed a Balrog" territory once you get beyond the primitives.
I've got a fully functional compile-time dependency injection container that I've been sitting on for literal years because the transformer API isn't public.
Typescript is mature. There is no low hanging fruit to be develop.
I don't necessarily think it needs this but this is hardly the right grounds to dismiss it.
(So as it turns out having thought about it a bit, I am vehemently against this idea.)
Type reflection at runtime would require polluting the JS environment with a lot of cruft.
That might be a global object and lots of helper functions to query types. It might also be tagging objects and fields with additional properties that need to be treated as reserved.
There is certainly no way to do this that doesn't make assumptions about the runtime environment in a way that will cause a mountain of issues further down the line.
The other reason for my disdain is: the need to infer types at runtime is almost certainly indicative of an architectural issue with your code. If you aren't able to write viable code in a given context without requiring runtime type querying then you should step back from your intent and re-evaluate your code structure.
For example suppose I have a web request coming in and I have essentially just a string of input coming in on the body. I have an expectation of what it needs to be but there is a step where it is of type `unknown` and I need to convert it into `IMyHandlerInput`. Just casting it is obviously a bad idea and so now I need to essentially use some kind of library such as ajv to do json schema or jtd validation, _then_ I can cast it into my interface.
This is all fine but it definitely feels redundant to me. It would be a cool _ecmascript_ feature to essentially support, not runtime types per-se but syntactic _validation_ which can also be used by typescript to derive types automatically.
This is totally hypothetical but I'm imagining something like this for example:
```ts schema Example { @min 0 id: number
@pattern /^\w+ \w+$/
name: string
@future
expiresAt: Date
}const data: Example = new Example(JSON.parse(body)) ```
Something that the JS runtime can use to allow developers to opt-in to extensible validation which can also be used by the typescript interpreter to essentially derive types.
I write one of them (typedload).
If it's a union, it has a bunch of heuristics to guess right at the 1st try, but otherwise it will just try them all.