3 ms·
Not being typed in a untyped/weakly typed language like JS, is NOT a bug. Just because something is 'legacy' doesn't mean it's crap. It cauld be well thought o
by ehutch79 3y ago
Not being typed in a untyped/weakly typed language like JS, is NOT a bug.
Just because something is 'legacy' doesn't mean it's crap. It cauld be well thought out and easily maintained.
I've been dealing with a straightforward legacy api in JS. Trying to port it to typescript, the hard part is typing classes with dynamic propertied based on a schema. Has worked great in production for years. Well tested. I have to rewrite it to make it workin typescript apparently. going from about 10 line files to 50+ just for typings. Im sure i'm doing something wrong, but i've asked and it seems my code is wrong? despite having worked great for me all this time.... Yes i'm salty
- jeroenhd 3y agoYou can use weak typing and dynamic programming to accomplish some impressive feats, just like you can write bug-free C code without undefined behaviour. It's difficult, especially when the code base grows over a couple of years, but it can be done. That said, some people see TypeScript as "Javascript, but with types in the definitions", but it's more than that. Sure, the core of it is that you're adding types to your code, but with things like KeyOf<>, Partial<>, Pick<> and other such utilities the TypeScript system is a lot more powerful than that of many statically typed languages. Typing dynamic JS with TS can be tough because complex dynamic typing requires a lot of assumptions that often are half-truths from a programming language point of view. "When x.foo is a Number then x.bar.baz is a String with at most two characters" can be expressed in Typescript but it's very verbose and requires some digging through the Typescript docs to get right. Describing types does add more lines of code, but that's not necessarily a bad thing. What you're doing is taking the implicit assumptions based on your dynamically typed program and expressing them in a way that can be verified. Assuming you don't invent completely new types in every single function, the initial typing workload is high but it becomes a lot easier over time, especially if you use your Partial/Pick/keyofs well. What I found to be helpful is that the ?. operator has been added to Javascript quite some time ago (legacy JS doesn't normally use it) which means you can define properties that don't exist in the beginning but are set down the line to be of type `foo: string | undefined` rather than invent implementations of interfaces for every modification step of the program, using it through `bar.foo?.baz` rather than `bar.foo.baz`, and maintain the exact same assertions your program had before. Alternatively, using `!` when you're absolutely 100% sure some parameter has been filled in (`bar.foo!.baz!`) can help convince the transpiler of assumptions that can't easily be expressed in code.