5 ms·
Which is the nature of the compiler. It maintains the promise that what you're writing is still JavaScript—in that you could just strip all the type annotations
by 52-6F-62 6y ago
Which is the nature of the compiler. It maintains the promise that what you're writing is still JavaScript—in that you could just strip all the type annotations and have valid JS.
But I would love runtime checks for types. Even if that was a compiler step I could flag on—but that makes it a great deal more complex both to implement and reason about, likely—without starting fresh anyway.
- phpnode 6y agoA while ago I built this exact mechanism for Flow, it could be done in TypeScript if there was enough demand for it (it's rather a large effort) https://gajus.github.io/flow-runtime/ https://gajus.github.io/flow-runtime/
- vorticalbox 6y agoI was thinking about this the other day i would love for TS flag that would turn an interface into an assert const shout = (message: string) => console.log(message) into something like const assert = require('assert'); const shout = (message) => { assert(typeof message === "string"); console.log(message); } of course this doesn't work for more complicated types
- IggleSniggle 6y agoYou should checkout myzod, which is very close to this experience.
- colinmcd 6y agoOr just plain zod
- IggleSniggle 6y agoGenuinely curious, why would you pick zod over myzod?
- vorticalbox 6y agoThanks for this
- mypalmike 6y agoWhy do you need runtime type checks if the compiler already checked the type? IMO, runtime type analysis is a code smell. There are few scenarios where the simpler and more efficient solution involves querying type metadata at runtime. Particularly in a language that directly supports dynamic dispatch, you should think hard before adding anything resembling an "if typeof(mything)" check.
- wolfgang42 6y agoThe obvious use case is the interface between something that’s not type-checked by the compiler and something that is. It’d be useful to be able to do `runtime_cast<Foo>(JSON.parse(foo_json))` on, say, the response to an API call and know that the result was definitely a valid Foo without having to write a bunch of boilerplate to validate that by hand. (Reading through the thread, there’s apparently some libraries that can do this; I’ll have to try them out next time I need this.)
- int_19h 6y agoBecause there's no guarantee that compiler did that. Even if you do this in your code, the moment it gets called from pure JS, all bets are off. With proper runtime checks, you could get consistent behavior out of that.