Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It is easy. It's just a terrible idea.

(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.



I mostly agree, having every single type checked all the time like other static languages is not appropriate and probably not even a good idea but on the other hand it is also kind of annoying to have your validation code be divorced from your types totally.

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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: