by paxys · 3y ago · 0 comments
> I love you. You do amazing work. You are gods among mortals. You have brought JavaScript from the darkness, and given it the warm light of strong typing. Look upon us, the cowering meek masses, and understand that we live in the muck and mire of a world where we are doomed to endlessly crawl on our bellies through the alleys of Github seeking the one true npm. We will forever wonder in the dark, until we have a type reflection model.
What even are they getting at?
As for their actual ask (runtime type safety), it is probably not going to happen because the TypeScript project has drawn the line at not being an alternate or additive runtime for JavaScript. Their job is simply to compile down to JS code and exit the picture. Whatever happens after that (in V8 or elsewhere) is your own business.
> TypeScript Needs to Emit Runtime Type Information
This is not possible at all because TypeScript is a compiler. They are really asking for a net new product which has very little to do with the TypeScript that exists today.
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 would be to use /compile time/ reflection to generate code (TS code hypothetical, because I write C++ nowadays):
function validate<T>(obj: Any): T | null {
switch constexpr (T) {
case String:
return typeof obj == "string" ? obj : null;
case Array<U>
if (!Array.isArray(obj)) {
return null;
}
for (const u of obj) {
if (validate<U>(u) == null) {
return null;
}
}
return obj;
// ... more base cases
}
for (const prop: (keyof T) of Reflect<T>.Properties()) {
if (validate<T[prop]>(obj[prop]) == null) {
return null;
}
}
return obj;
}
interface Date {
year: String;
month: String;
day: String;
}
It would be great if this could generate /JavaScript/ code: function validate__String__(obj) {
return typeof obj == "string" ? obj : null;
}
function validate__Array$Date$__(obj) {
if (!Array.isArray(obj)) {
return null;
}
for (const u of obj) {
if (validate__Date__(u) == null) {
return null;
}
}
return obj;
}
function validate__Date__(obj) {
for (const prop of ["year", "month", "day"])) {
if (validate__String__(obj[prop]) == null) {
return null;
}
}
return obj;
}
Unfortunately this is not possible (AFAIK) in TypeScript currently, and will not be possible with TypeScript's current philosophy.(The above example is a hypothetical TypeScript compiler that might support "templated" generic functions; with just RTTI TypeScript could accomplish the same thing in a non-templated function by passing in `T` as a function parameter at runtime and doing runtime comparisons on `T`.)
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.
The only place you need runtime type enforcement (when you're writing your own code in TS) is for validating third party data at the point where you're ingesting it into your own code. Once it's in there, it is type safe if you used TS to compile your code to JS, because your function calls and data copies and everything else that moves data around was defined in terms of compatible shapes.
And we already have runtime validation libraries to cover that validation step. So many of them.
Right, but now my type information for inbound data must be in two places: the typescript type, and the validation schema. And heaven forbid I make a mistake and those two become out of sync.
Yes, I can use something like zod to define a schema then infer the type from it, but those inferred types are often … suboptimal to work with.
Alternatively, use a runtime validator the provides good type inference out of the box so you're still only declaring your types once.
And even if you are--that might also involve ensuring their tsconfig.json is compatibly similar to yours. Otherwise the compiler might allow them to return null instead of the object they say they return, among potentially many other "gotchas" that are bound to appear.
EDIT: Though I think I do agree with you, ultimately. Runtime type checking imposes non-negligible costs and complexity that still theoretically should be able to be guaranteed at compile time for cases where one isn't validating untrusted user input.
Did you read the article? I think that's the point. The premise is Typescript should be responsible for solution to runtime validation against Typescript not third party hacks.
schema Example { ... }
cosnt example: Example = new Example(unkonwnData)
Where a schema applied runtime validation based on declarative syntax and which typescript could use to derive a `type` fromWell that, and getting rid of the silly "must be able to strip types without processing them" design ideology would also enable stuff like typeclasses.
To the extend that TS's type-system is unsound, and everything may crash at runtime at random anytime.
They just serve burgers and fries. And they are doing very well with that strategy. Same goes for TypeScript.
TypeScript is a compiler. It has a lot of type information during compilation. We could write that type information out into a file. Instead what we do is throw that information out when the compile ends. Taking all that typing information & throwing it away at the end of compile time is a bad dumb & silly limitation. Especially for a language like JavaScript, which historically could be semi-proud it had such a strong Everything Is An Object philosophy running through it (such as the malleable prototype-based inheritance system); so much type information should be on that Class object. Reflect-metadata for example defined new methods on Reflect to store this metadata.
I could not be more delighted to see the pennon of this website go up. We needed a rallying point for this. We needed a rallying point for keeping class data around. A rallying point for enriching the runtime with good actionable data is a good rallying point.
It's not what's afoot here, but I think you're a bit off-base about the impossibility of adding even some type-safety. We might not be able to get exact TS type safety. But we can definitely build some safety in. Owing to the malleable prototype-based type system in JS, we can add getters/setters to objects to do a lot of type checking. This doesn't even begin to explore the possibility of what we might do with es2015's proxies, which could allow even more interesting checks to be layered in. I also wish JS had an official AST (and renderer), so had more official options for code-rewriting that might let us weave in type checks.
What we can do as programmers is limited by what we have at our disposal. Not throwing out all the typing information, keeping it around at runtime, opens a lot of interesting doors.
Some people have very tight constraints for payload size, and types could blow up payloads
Conceptually it feels like there should be/needs to be some buy in on high, a shared vision that tsc is not the one, only & singular tool in the typescript-verse that ever can or will care about types. Trying to constantly break in & exfiltrate the data isn't ever going to get a position where the world takes this seriously; typescript needs really should gladly be opening the gates.
As for whether the type information is in fact part of the payload, that's a separate question, and one that should ideally be configurable. It's definitely a bit of a complex situation in general; ideally we'd have good/easy ways for libraries to include this information but then we also want want to be able to strip it out easily.
Maybe we just regenerate it as needed from ts source of libraries when we need it. But that implies not running a single typescript compile with one set of settings but running many compiles, as each library has its own tsconfig it'll need that informs how files are laid out & other sundry details. I might be overcomplicating. Perhaps we could just generate a foo.reflect.js, that has all the reflection data? There's options.
That's not correct. All you would really need to do is output type information as JS objects and then support reflection libraries that looked up information at runtime. Two examples where this already happens:
1. TS enums are output as JS objects, as opposed to, for example, string literal union types. That is, "enum Foo { Bar = 'BAR', Baz = 'BAZ }" outputs information that can be queried at runtime, while "type Foo = 'BAR' | 'BAZ'" does not.
2. TS already supports runtime type guards functions, https://www.typescriptlang.org/docs/handbook/2/narrowing.htm.... It wouldn't be hard to generate those functions automatically using information already in the type system.
1. I was responding to the point that seemed to be arguing that just because TS is a compiler (to JS), that it couldn't support runtime type info. That's incorrect, and different from the current philosophy of "TS should really only use type erasure when outputting JS code".
2. After many years I've come to the conclusion that there is huge benefit for an ecosystem to either (a) have a "batteries included" mindset, or (b) have a way to "semi-officially" designate associate libraries as being supported. I think Java really excelled here. For example, the Java Collections library was/is excellent, and for a long time (not sure if it still is, I've been out of the Java ecosystem for some time now) Apache Commons were the go to place for libraries everyone used. Contrast that with the Node/JS ecosystem, where basically "whatever gets the most popular in NPM" becomes a semi-standard, but there are still often 5 competing libraries, and until the module owner decides to delete a widely used library or just stop releasing updates - besides leftpad infamy, there was also an issue where lodash basically went unreleased for a long time despite needs for critical security patches.
When it comes to TS, I understand the guiding principle of "we only implement type erasure", but I wish there at least a way to e.g. set a tsconfig flag if you wanted to allow runtime data, or to have the equivalent of Apache Commons for TS.
I only skimmed this but felt it was clear. They're asking for TypeScript, as part of the type erasure, to emit the type information it has discovered about the types in a side channel to the emitted JavaScript. Think of, say, PDB files as an analogy.
> They are really asking for a net new product which has very little to do with the TypeScript that exists today.
This is information TypeScript already has today but which it discards. It wouldn't take a "net new product".
The level of detail TS has about types during the checking phase is much higher than you would want in practice for 99% of projects (e.g. 1 + 2 + 3 has 6 different types associated with it).
The level of detail TS has about types during the checking phase is potentially lower than you would want in practice for a lot of projects (which is critical since that makes the whole feature useless if that happens). For example, the list of properties of a particular generic instantiation is lazily computed, but it's possible your program never pulls on the list so it never exists in the first place, yet is something your type-based tool might want to know.
> This is not possible at all because TypeScript is a compiler.
Sorry, can you clarify? Many compilers exist in other languages that support RTTI, so it's not clear to me what you mean by this.
Not sure if this supports your point. Lots of compilers emit runtime type information, e.g. Golang, Java.
I do think theres room in the world for typescript to be able to emit runtime code from its types, but I don’t think it should be in the business of writing validation libraries.
Closest they should get to this work is writing an interface to export types types into runtime code that another lib can pick up and write validators with.
The only missing link is then that Javascript objects don't know their original Typescript type, that would need to be magically injected by the TS compiler as a custom property.
How useful that would be in practice, no idea... I can pretty much only see downsides (mainly increasing bloat).
Also the same thing can probably be implemented in 'user space' by a tool which parses .d.ts files and code-generates such type-database modules from that information.
I don't understand. Go is a compiler too, but here's https://pkg.go.dev/reflect