Live data from Hacker News

TypeScript please give us reflection/runtime types

github.com

151–160 of 287 posts

Re: TypeScript please give us reflection/runtime types

#151

Earlier quoted context omitted.

Nit: they're not asking for runtime type safety; they're asking for the ability to reflect on types (at compile time, to generate values) so that they can use type information at runtime. This helps ensure runtime type safety because (for example) it would be great to have a generic "validation" function that takes an arbitrary interface and an arbitrary object and validates that object. One way to implement this wou…

Not to be flip, but if it were really all this easy, we would have done it already. 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 f…

Can we just start with primitives and see what happens.

Re: TypeScript please give us reflection/runtime types

#152

Hey all, TypeScript PM here. I understand the desire here. Runtime type checking is often necessary for data validation, and we can see lots of libraries developed to help fill the gap here. But I think the fact that there are so many libraries with different design decisions is pretty indicative that this is not a solved problem with an obvious solution. We knew this going into the early design of TypeScript, and it…

Maybe official preprocessor plugins for TypeScript compiler could help? I understand that everybody who needs it can already put their own preprocessor that generates runtime objects from type information before the code is passed to tsc for compilation. But the effort is inconsistent and distributed. If TypeScript officially supported pluggable preprocessor and plugin ecosystem for it some good solutions might get d…

What's next? An official TypeScript UI framework, will it be Vue, React, Next.js or Svelte? An official TypeScript date library?

Re: TypeScript please give us reflection/runtime types

#153

Hey all, TypeScript PM here. I understand the desire here. Runtime type checking is often necessary for data validation, and we can see lots of libraries developed to help fill the gap here. But I think the fact that there are so many libraries with different design decisions is pretty indicative that this is not a solved problem with an obvious solution. We knew this going into the early design of TypeScript, and it…

I'm relatively new to programming and had a question about TypeScript's functionality. Is there any specific reason why TypeScript doesn't allow for the creation of custom and intricate data types? For example, I'm unable to define a number type within a specific range, or a string that adheres to a certain pattern (like a postal code).

I'm imagining a language where I could define a custom data type with a regular function. For instance, I could have a method that the compiler would use to verify the validity of what I input, as shown below:

function PercentType(value: number) { if (value > 100 || value

    return true;
}

Is the lack of such a feature in TypeScript (or any language) a deliberate design decision to avoid unnecessary complexity, or due to technical constraints such as performance considerations?

Re: TypeScript please give us reflection/runtime types

#154
post #60

Earlier quoted context omitted.

Yes, but it's special in that it compiles by erasure. (Mostly -- the cases where it doesn't are considered historical mistakes.)

Ok. And why is that important? So one could meticulously add typing to your JavaScript application, and then strip it all out with a regex in order to deploy? What real-life benefit does 'compile by erasure' offer?

I think the point is that TypeScript isn't really "a new language". It's an existing language with an additional feature. The fact that TS maintains the promise that types can be stripped means that TS is upholding a contract that it will not stray from Javascript. It can't, for example, add new language features.

Re: TypeScript please give us reflection/runtime types

#155
post #141
post #61

Earlier quoted context omitted.

Javascript already has standard serialization and deserialization tools. The problem is that the deserialization is untyped. It's just a Javascript object. Usually, the first thing you'll do is to cast it to a typed Typescript definition, but there's no way to guarantee that it actually fits that definition. No type information exists at runtime. It's used solely to check the code itself during compilation. So any ti…

It's basically the same for typed languages. If you want to map JSON to a typed data structure, you need a serialization library to do that. JavaScript has a very simple built-in json reader/writer that does no type checking and returns some nested dictionaries or arrays. If you want more, you need a library (for example zod). Or you just trust the data to have the right shape.

Java has runtime type definitions, which you can use to automatically type check deserialized objects. With reflection you can write that in ordinary Java.

I imagine C# and other Java-esque languages have something similar. But Typescript deliberately avoids that, and it would be difficult to get it to do so.

Re: TypeScript please give us reflection/runtime types

#156
post #18

I’m mainly a backend programmer, so I know just a little typescript, but I don’t really understand what they’re asking for here. It sounds like they want to serialize and deserialize typescript types automatically? If so, that sounds like a good fit for a library, not something most languages offer. (Please educate me if I’m missing the point)

There is currently no good way to automatically validate the object input to a typescript API. In the way that you can simply specify the class of a POST body to a spring boot controller or Asp.Net controller, every class in typescript requires you write the type information twice: once for the typescript compiler, and once again for the runtime deserializer, in the form of decorators. Having to write extra code to make up for a deficiency in your framework, runtime, or language is the definition of code smell. As such: all typescript backends which attempt to properly validate user input are guilty of egregious codesmell.

Additionally, because it is impossible to emit these types to the runtime, even in the form of a string naming the type, you cannot validate input to an API using generics. If you have, say, a class which will run a query for a record based on the keys in that record:

    class Query{
        filter: Array
    };
The typescript compiler can validate if a string in "filter" is, in fact, a key of the class T. However, you cannot write any decorator on this class to make the information of what keys exist on T available at runtime. Therefore, to write such a query interface and validate it at runtime, every record which can be queried with this object must have its own specific "[Record]Query" class written with its own decorators to validate every possible input, usually with the valid keys hardcoded into the decorator.

Because there is no real relationship between the class and the runtime validators, this makes validation more error prone, because it relies on either human beings to consistently remember to add new fields to the relevant decorators, or a custom linting tool to be written which basically pre-processes the typescript source using the typescript API. This is, again, writing code to account for the lack of features in the framework.

WHY do we put up with this crap? We have had Java and C# for a long time, and they solved these problems a long time ago. Why are we writing Typescript on the backend?

The simple answer; it is easier to find javascript developers than it is to find java developers. Bootcamps don't teach Java or C# because there's more react jobs out there. Bootcamp grads are not generally coding enthusiasts and so re-tooling is difficult for them and they don't generally do it for fun. So, we decided to write our backend in Javascript (or Typescript) as a labor decision, not a technology decision.

Re: TypeScript please give us reflection/runtime types

#157

Earlier quoted context omitted.

Not to be flip, but if it were really all this easy, we would have done it already. 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 f…

Can we just start with primitives and see what happens.

JavaScript already has this. It's called typeof.

Re: TypeScript please give us reflection/runtime types

#158
post #145

Earlier quoted context omitted.

The reason we want typescript to have java-like features is because we work on teams which have decided, outside of our control, that we are going to write our backend in JS/TS simply because it's easier for the bootcamp grads to transition to backend since they already know JS on the frontend. If we wrote our backend in Java, it would require the bootcamp grads to learn a new language, which they're not prepared to…

So you want TypeScript to be Java, but you don't want to use Java, because your developers only know TypeScipt. Sounds like an unsolvable problem.

The solution is to pile features onto typescript that were never intended to be there, the same way we have done with Javascript, HTML, CSS, and HTTP. None of these things are pure, and all of them have been ravaged by competing interests and committees who were all making financially driven decisions when writing the standards.

It would be best to abandon javascript and typescript as backend languages. I don't mind them on the frontend because a typescript compiler is useful when the application you're writing is originating data and not receiving it. And javascript does DOM manipulation admirably. However, we live in a world where humans are more expensive than computers. If I had my way, we'd write C# backends and Angular/Typescript frontends, but that's not the world we live in. Everything has to be JS because most people employed as "software engineers" are not truly very good at their jobs

Re: TypeScript please give us reflection/runtime types

#159
Fairly recently I built a C library for object serialization, based on run-time reflection. Run-time reflection is not necessary to the task and makes it perform worse than a code-generating solution.

The run-time reflection approach is good in one way: it doesn't add tooling to the project. All the modules that use serialization have to make a bunch of tedious API calls to build the type object which represents the C structure. This is created once and stashed in a global variable. Then it is used as a parameter when serializing and deserializing.

There is a performance impact because the marshaling code is interpreting the type object; it recursively walks the type object, and in parallel it walks the C object to extract or stuff material.

A generative approach would just write a serialization and deserialization stub. There would be no need for any type object to be walked at run-time. No need to construct such objects at startup and no need to carry the library for that.

But there would be some tool which itself has to be compiled (for the build machine, not the embedded targets), and then some Makefile steps to run that tool on some interface files. The thought of inflicting that one the project made me go yuck.

A third possibility is to have the run-time type info objects, and add JIT. Why do something easy, like a code generation tool called out of Makefile, when you can do something hard and nonportable?

Re: TypeScript please give us reflection/runtime types

#160

Hey all, TypeScript PM here. I understand the desire here. Runtime type checking is often necessary for data validation, and we can see lots of libraries developed to help fill the gap here. But I think the fact that there are so many libraries with different design decisions is pretty indicative that this is not a solved problem with an obvious solution. We knew this going into the early design of TypeScript, and it…

I'm relatively new to programming and had a question about TypeScript's functionality. Is there any specific reason why TypeScript doesn't allow for the creation of custom and intricate data types? For example, I'm unable to define a number type within a specific range, or a string that adheres to a certain pattern (like a postal code). I'm imagining a language where I could define a custom data type with a regular f…

Some of this is possible in the type system like a range: From stackoverflow: https://stackoverflow.com/questions/39494689/is-it-possible-...

  type Enumerate = Acc['length'] extends N
    ? Acc[number]
    : Enumerate

  type NumberRange = Exclude, Enumerate>

  type ZeroToOneHundred = NumberRange
One limitation is that this has to be bounded on both ends so constructing a type for something like GreaterThanZero is not possible.

Similarly for zip codes you could create a union of all possible zip codes like this:

  type USZipCodes = '90210' | ...
Often with the idea you have in mind the solution is to implement an object where the constructor does a run time check of the requirements and if the checks pass instantiate the instance and otherwise throw a run time error.

In functional programming this is often handled with the Option which can be thought of as an array with exactly 0 or 1 elements always. 0 elements when a constraint is not met and 1 element when all constraints are met.

This [0] is a library I wrote for JS/TS that provides an implementation of Options. Many others exist and other languages like Rust and Scala support the Option data structure natively.

[0] https://github.com/sbernheim4/excoptional

Post reply on HN