339 points · by shian15810 · 6y ago · 270 comments
Editors give great autocomplete suggestions (usually covers it for properties and return values). Documenting with examples is often helpful. If all else fails, cast.
Without advanced types, code needs documentation to prevent invalidity. With advanced types, code gets logical guarantees, but it often requires the same documentation. It's not necessary for everyone on a team to have cutting edge knowledge when there's sensible documentation.
Types create a synergy with documentation. Provable(ish) guarantees with good documentation is the best of both worlds.
Part of it is just being able to write code that is extremely dynamic, yet still provides an amazing developed experience.
For example if an API change occurs on backend, the first step is to make the change to the request/response typings in the frontend...from there the source code will light up with all the errors you have to fix. I can just click through each one in VS Code and fix them, then re-run tests to validate...love it.
Much more effective.
The dynamic JS space uses things like JSON Schema because they provide documentation and enable runtime validation, in a similar way to libs like io-ts. But they also provide API/network boundary documentation, as well as enable automatically generating client libraries (regardless of the client’s stack).
There’s a good opportunity for a library with all of these value propositions:
- simple, declarative, composable definition interface
- runtime validation/decoding/encoding
- DRY static type generation
- DRY standards-based documentation generation
There are (to my knowledge) no tools available providing all of those in one package. But I’ve built one (it was built on top of io-ts), so I know it can be done. But it was proprietary, for an employer, so I can’t share it.
But! I learned a lot in the process, and I’m building a new one. Zero dependencies, fundamentally a different design/approach. But I’ll definitely be sharing it with HN when it’s ready.
Edit to add: another thing is that many of the tools that provide some subset of those goals (especially static types <-> JSON Schema tools) require is out of band code/file generation (eg supply JSON Schema file input, get .d.ts file output, or vice versa). IMO this is additional DX friction and more error prone than the runtime/compile time parity of the common TS libraries. So another goal for my project is that the default approach is to define one interface and have APIs available to access all the other representations in the same flow, with file generation a secondary concern if there’s a need/desire.
I mean one can't represent the all possibilities of JavaScript "types" without re-implementing JavaScript itself, only a subset. I wonder where Typescript will stop.
I'd like to see Typescript compiling to "native" as well.
You don't have to personally understand TS's more complicated features to benefit from using TS in your project. I hope they continue adding richness to the type system so I can eliminate more bugs from my code.
I'm not sure what you mean by "in the flow itself" exactly, but just yesterday a teammate of mine was using one of our libraries in a small project without TS. They first called getThing(), which might return null, and then passed the result to doSomethingWithThing(), which did not expect a null. That sounds like a "flow" problem to me, and TypeScript literally would've warned them of it.
(Since this particular combination of functions is likely to be common, we added a runtime check for people who aren't using TypeScript now.)
> Most devs using it have never seen vanilla js and are more java minded that prototype minded.
I think you might be underestimating the number of people who strongly dislike Java's type system but very much appreciate TypeScript. They're very different, and hence it's very much possible to like the latter for reasons that do not apply to the former, or to dislike the former for reasons that do not apply to the latter.
1: http://earlbarr.com/publications/typestudy.pdf 2: https://www.reddit.com/r/typescript/comments/aofcik/38_of_bu...
It's not only your stereotypical Java developer who has to maintain large code-bases. There are much more monolithic code-bases than there are micro-services. Also, probably you have a much better memory than me, but I, like many others have trouble working with random objects with no contracts.
Additionally, try using a library like io-ts and you also get validation against types.
Typescript made me love JavaScript again.
But my gripe with Javascript has always been, that you often don't get any direct errors at all but instead end up with unexpected values in a different place that you then have to tediously backtrack.
A contrived example to illustrate what I'm referring to:
some_obj = {day: 2, ...}
next_day = some_obj.daz + 1 // typo in attribute gives you `undefined`, adding 1 to it results in `NaN`, not a number.
date = Date(2020, 11, next_day) // returns a`Invalid Date` object
console.log('date: '+ date) // outputs "date: Invalid Date"
In Python, every line after the first would raise a runtime exception and is thus in my opinion much easier to debug.What I particularly like about Typescript is that I can use as much or as little of it as I deem necessary. E.g. I start off a prototype using the `any` type a lot, and only in future iterations, I start tightening the definitions as the requirements for the project become clearer. So far the overhead has been quite minimal.
The one downside so far is, since I learned Typescript by just starting using it, without a deep dive in documentation, books, etc. trying to grok code, well especially type definitions of libraries (which I often prefer over reading documentation) that use the more advanced features has been quite a challenge.
Also, reliable auto completion is very helpful not just for the method names but for properties etc.
Personally, I have no issue with TypeScript purely as a language and I concede that it provides much better IDE code completion than JavaScript. That said, I don't agree that its benefits offset the drawbacks of the transpilation step, the source mapping and the added versioning complexity between JS and TS.
I also miss the way that JavaScript encouraged people to define very simple function signatures (e.g. strings, numbers, plain objects/clones as arguments and return values).
For example, I really liked how the React/Redux community came up with a philosophy around cloning state objects before returning them from functions in order to prevent unexpected mutations later (essentially force everything to be pass-by-value). I think this philosophy does not translate very well to TypeScript which encourages developers to pass around complex live instances (which have their own methods) instead of raw objects and other primitive state representations.
As Alan Kay pointed out, OOP is not primarily about objects, "The big idea is messaging". Instances should communicate with each other via simple insterfaces using simple messages; they should avoid passing complex live instances to each other. If an instance has methods, that is a complex live instance and it shouldn't be used for messaging between different components.
Some of the bugs exposed were the bugs in the 'flow'.
But when testing properly, these should anyways be found later. Or am I missing something?
It's great that Typescript is catching on, and we're starting to adopt it in my team, but I hope the TS people don't think they can keep adding new features to it in perpetuity, otherwise it's going to turn into C++.
In other words, typescript doesn't make the language any bigger. If you're struggling to understand typescript code you could just ignore the types, and you're back with regular JS. This is different than the issue some people have with a big language like C++, where the sheer number of features can make it hard to get a grip on unfamiliar codebases.
Stage 1: Put types into JavaScript.
Stage 2: TypeScript types are not expressive enough.
Stage 3: Put JavaScript into types.
I'm looking forward to stage 4 where the expressions inside TypeScript type annotations get so complex and hard to maintain that someone creates TypeTypeScript that lets you put type annotations inside the code inside type annotations.
https://github.com/capsadmin/nattlua
You can see some examples in the readme.
To me it makes sense that the typesystem is basically lua rather than a mathematical ish looking language.
It could prove to be more difficult to work with but I guess I'll find out.
It's not without precedent - Haskell has a Turing complete type system. (There's also Scala, Rust, and C++ templates which are all arguably Turing tarpits.)
I don't think my comment sounds cynical.
> You don't have to use features you believe are "so complicated".
One has to be fluent with reading type definitions thus have good understanding of the type syntax. I must admit, from time to time I could not make sense of them easily when reading declaration files from third parties.
If you ever do have to dig into a really complex type, that might be painful, but keep in mind that the reason we have more sophisticated types is so that we can maximize correctness and reduce the chance of bugs, the fact that you're getting a type error at all means whatever you wanted to do is definitionally unsafe, so it's good that typescript is empowered to tell you not to do this, even if you don't immediately understand why.
That makes sense when comparing it to other languages, but compared to JavaScript: those type definitions are a pure bonus? In other words, if they'd have been written in JavaScript you'd still have to make sure to pass in the correct data, but you'd have only the documentation to guide you there.
(Of course, if you yourself are using TypeScript, you do have to know how to make sure that TypeScript knows that you're passing in the correct data. But the flip side is that the more complex types will allow for better inference that helps your editor to provide better guidance on how to give it the correct data.)
TypeScript advanced types are there to model existing JavaScript codebases, but when designing software from scratch I've seen that is too tempting to go crazy with the types, ending with something pretty messy (JavaScript! :-).
> [A Static TypeScript] program is compiled to machine code in the browser and linked against a precompiled C++ runtime, producing an executable that is more efficient than the prevalent embedded interpreter approach, extending battery life and making it possible to run on devices with as little as 16 kB of RAM (such as the BBC micro:bit).
To give a commonly-encountered example, rather than the easily-introspectable options object whose schema is specified by a zero-runtime-cost TS interface, in a traditional OOP language like Java you would write an XOptions / XOptionsBuilder class to maintain type safety, which is at once more opaque, with less predictable behavior.
It's not a horrible abuse if you aren't trying to make the framework/library statically typed in the first place.
Idiomatic APIs for dynamically typed languages use the flexibility of dynamic types. Idiomatic APIs for statically typed languages use the structure of static types.
The problem comes when you try to put one into the other's world. It's like watching a fish flop around on land. There's nothing intrinsically wrong with fish locomotion, it's just not optimized for that environment.
Of course it is, because even if there's no type system the people using the library still have to make sense of the complexity. A function with a dozen, context-sensitive overloads that accepts data without a clear pattern isn't just hard to type, it's also hard to understand for a user. Even with dynamic typing you should be able to clearly state what a function does.
That's why, even if I don't plan on using Typescript itself for a project, I prefer libraries that have type declarations or are natively Typescript. It shows the library authors at least attempted to understand the type system they were creating.
Haha, great way to put it
Except all of it can be tested and validated at compile time so... not dynamic?
When some programmers favored dynamic languages over the statically typed others looked at them like at mad.
The thing is that dynamic languages fans just wanted to have semantics as rich as this one and were willing to sacrifice even type checking altogether for it because no statically typed language was willing to deliver this semantic in any reasonable manner.
[0]:https://github.com/DefinitelyTyped/DefinitelyTyped/blob/mast...
In years of using TS I have had to craft a few exotic generics, but have otherwise never ran into "really complex" types.
https://github.com/DefinitelyTyped/DefinitelyTyped/tree/mast... felt like to me as one popular example for what should be really simple in practice.
You end up with write only code that while typed is overly complicated.
The semantics of a number or a string aren't described by their basic type.
Yeah I'd love something that just compiles .ts to a binary. But I can already hear the cries of "embrace, extend extinguish" if that happened.
https://www.typescriptlang.org/play?ts=4.1.0-beta#code/PTAEB...
Something like -> "Hey! it looks like your function only accepts a fixed set of strings. Would you like to use String Literals?"
I don't only code in Typescript so it's not practical for me to keep up with every language I work with.
Search works great if you know what you want, then you'll end up on these excellent release notes or a stackoverflow post and off you go. The trouble is when you don't know what you don't know.
For example, with an opportunity for string literals, there will be a light bulb in the left border. Pressing "Ctrl ." will bring up a list of suggested fixes. You can opt to select one, hit Enter, and the changes are automatically applied.
I believe there are similar extensions for VS Code.
Review early and (fairly) often, lest you embark on implementing a FrobNibulatorFactory from the ground up only to be told there is one already in lib/util/frob/util/tools/misc/nibulation.
Not everyone has peers, alas. The imaginary ones help (rubber ducky, you’re the one...)
.NET's Roslyn compiler supports analyzers that you can write yourself which also support code fix providers to automatically refactor code. All analyzers and code fix providers are written in .NET languages (C#, F#, etc.), so the possibilities are endless.
The Rust compiler exposes a lot of information, so it's actually quite powerful in my experience.
[0] https://marketplace.visualstudio.com/items?itemName=ironcev....
At least the pain is a good indicator that there's something you're missing :) IRC has been somewhat useful for TS, albeit with mixed results compared to say, the gentle gods you will find in #postgresql.
Having worked with Clojure for 4 years, and a JS (ES6 and +) codebase, static typing is amazing.
There are far fewer bugs at runtime because of incorrectly setting or forgetting to set keys in a map or a property or accidentally passing the wrong value to the property. Yes, interop with JS is a little messy, because of the dynamic nature of JS, but a large class of errors can be significantly reduced by Typescript.
As for the argument , unit tests can catch most of the problems Typescript solves, my counter is that
It reduces the amount of tests you need, to check getter/setters,types etc SIGNIFICANTLY. You can focus your unit tests on the more functional aspects than having to worry about basic property access.
All high-level languages have a learning curve. I don't expect to pick up the nuances and all the little bits of Typescript in a matter of weeks or months.It might even take years, but I think Typescript and its experimentation with providing a well typed Frontend interface is amazing !
Exactly! unit testing a return type is such a backword step in programming
When you wrote/write Clojure, did you ever use spec? Any insights into how it compares with TS? They seem to give similar guarantees for this aspect, but I haven’t played with spec yet.
spec , IMHO, seemed oriented towards validating properties and values in maps, as Hickey mentions in his talk, it is all about manipulating data.
Spec is opt-in. unless you are working with code that has already been spec-ed , you will run into the same problem that TS + JS interop has.
I found spec a little too intrusive (especially the namespaced keywords) and sometimes I wasn't sure what it was meant for, TBH.
In my first company, it was a bunch of cowboy programmer that didn't really care about typing the codebases, too cool to write unit tests and simply wrote enough end-to-end tests cases to solve the problem. I was just starting out and had NO idea on what was good programming practice.
In the second firm , we had used schema to type the codebase partially and it worked. But the type checks weren't compile time , but rather during unit tests and when running with type-checking enabled (I think this is the same for spec as well)
I think the advantage of TS comes from the static types (+ checking). You get immediate feedback before you can even compile it into javascript.
Why is alignment accepting a color? It doesn’t matter how good the type checking is if you are creating the wrong type to begin with.
That aside, congrats on the release!
By any other name would smell as sweet.
So Romeo would, were he not Romeo call'd,
Retain that dear perfection which he owes
Without that title.
https://davidtimms.github.io/programming-languages/typescrip...
- more accurately and more maintainably typing existing JS interfaces
- enabling more advanced compile time features for libraries
I’m probably one of these “typstronauts” you reference, I have extensively used nearly every advanced type feature in library code. But I’ve seldom found a need for any of them in consuming code. My approach since I adopted TS has always been:
- libraries can and should provide types at whatever level of complexity necessary to make library usage flexible, safe and simple
- end product code should use simple types wherever possible and depend as much as possible on the flexibility, safety and simplicity of the interfaces provided by those more complex libraries
I hope I never have to use it but that its existence makes typed libraries more "correct".
e.g. get({ name: 'Toby' }, "name.prop1.prop2") would fail as you're trying to call .prop1 on a string.
Really blew my mind. I'm used to having to give up simple APIs like that when moving to a statically-typed language.
get({ a: { b: { c: ['foo'] } } }, a *> b *> c *> _0)
and a macro to unfold the lens from a literal string is probably something that exists as well.There are of course nice qualities of simple functional composition and custom operators, though it comes with another layer of overhead that you wouldn't necessarily always choose over a simpler API in every case. Richer typed expressiveness lets us pick the right trade-off without being forced.
It will be interesting to see if they add metaprogramming capabilities next (allowing anyone to create a class like Uppercase<T>), although I’m not holding my breath.
Edit: see this SQL made out of the type system: https://github.com/codemix/ts-sql
https://twitter.com/toolslive666/status/1309533781137780741/...
Agree with the general sentiment though.
I'm up to speed now, but I still feel I'm missing an opinion.
e.g. I have naturally been drawn to "maximally infer" types, whilst I see other developers would rather re-create/co-locate a type with its function/component.
Does anyone have a repo where they think the TS is near-perfect? Or even better, a deeply opinionated Style Guide?
I've been starting to build speed-focused TS type-checker that is intended to be used in single-file editors like VIM to highlight errors, because it starts checking from a single file and just traverses files necessary to check types within that one file. If you defined your types at a module boundary it can bail out super early, since it doesn't need to look at the rest of the code of that module at all.
Most linters have rules that will force you to explicitly declare types at module boundaries.
Other than that, do whatever you prefer.
- Ideally they should either not be derived types (using eg type parameters), or if they are they should be derived using types from the same layer of your project/service. This makes it much more likely you’ll notice if you introduce breaking changes.
- Types should also between network boundary layers and business logic, regardless of your module structure. This ensures your business logic’s interface is clear regardless of how it’s consumed, making it more easily testable and more portable (eg to other transport formats/protocols).
This seems... Wrong. Better leave a comment because other people might assume it's a leftover from a refactoring or such.
It's easy to get wrong since it overloads syntax (casting vs boolean ops) and is very hard to google (as many operators are).
https://stackoverflow.com/a/63867074
… for what is literally a one-liner elsewhere:
class User :ro {
has name => isa => Str;
has email => isa => Str->where('lc =~ /^[a-z.@]{1,32}$/');
}
User->new(name => 'Dave Morrison', email => 'Dave.Morrison@gmail.com');
User->new(name => 'Van Morrison', email => 'Van-Morrison@gmail.com');
User->new(name => 'Jim Morrison', email => 'Jim.Morrison.is.my.name.and.it.is.too.long@gmail.com'); export type Camel<T> = { [K in keyof T as K extends string ? `${Uncapitalize<string & K>}` : K]: T[K] extends Record<any, any> ? Camel<Exclude<T[K], null>> : Exclude<T[K], null> }In most other frameworks there seem to be some arcane incantations required to include typescript into the build system. I have not looked into this recently - is there a straightforward way of including Typescript into a Rails, Gatsby, Hugo, Laravel, Wordpress, etc. project?
I feel like Typescript popularity would explode if the above level of friction became near-zero.
I’m a fan of the Runtypes library for this use case. If you design your typescript interfaces using the library (admittedly a bit magical to me) you can get runtime errors if API data doesn’t match the expected type
The point of type-safety is to be able to describe more succinctly what the _programmer_ expects out of the code. As you said, when you get to production, "all bets are off". This still applies with any type-safe language. Types don't exist when you're compiling to machine code, either.
I'm not sure it is; the most dangerous things in programming are assumptions that are almost correct, so you don't notice the problem until it's too late. An error whose symptom is an Int actually being a String several files away from where the mistake actually happened can be harder to diagnose than the same error in a untyped language, just because it's so contrary to your expectation.
- Catch more errors at compile time
- Better tooling (better intellisense, “go to definition”, “find implementations”, etc.)
TypeScript provides both of these benefits just fine. Runtime types give you better runtime errors, and less undefined behaviour, but plain JS (or TS compiled to JS) does that bit just fine. TS types persisting at runtime could maybe be nice for certain use cases, like more powerful reflection, but that’s not type safety.
What’s a concrete example where your program would be more safe if TypeScript types were represented at runtime?
It also encourages better architecture in my opinion, as it forces you to reduce the importance of something being an exact type... As it's not strictly enforced at runtime.
If my parameter only accept "foo" or "bar" and that at runtime I send an invalid input, will I get a type runtime exception? Or will it silently allow the invalid input? If it's the former, that would be great news but then I wouldn't see the point in Io-ts, and where is the limit? Could they stop type erasure and allow generics reification?
> If my parameter only accept "foo" or "bar" and that at runtime I send an invalid input
calling a function with a general string argument when the parameter expects a string literal will have TS refuse to compile.
Most of the time you want to validate user strings/runtime generated strings. On most applications compile time strings are very few and not need validation. When you need validation of strings you generally need only runtime or both and then why duplicate the runtime validation with another compile time validation that take an alternative syntax? This seems 1) a niche feature And 2) a feature that users will misunderstand, the only dev I know which read about the feature think it works at runtime. Also I believe that existing template litteral do accept general strings I did a POC a few months ago so that's weird but maybe that TS can determine that a string is from runtime and then refuse it at compile time.
Some domains that will benefit: ORM mappers, CSS style generation, configuration strings, path munging, localization.
> Also I believe that existing template litteral do accept general strings I did a POC a few months ago
... yes, template literals accept general strings. Like I said,
> Template literals that contain non-string-literal parameters will still generalize to string.
the new feature kicks in when all the parameters supplied to the template literal are value types themselves, or an OR of value types (I don't know if something even more expressive is supported).
I hope you try to understand better what TS is offering before you make uneducated criticisms of it.
If you are strict, don’t intentionally try to outsmart the type system, and use manual runtime type checking when necessary [0], TypeScript does a good practical job of ensuring that you won’t run into runtime type errors.
The reason TypeScript doesn’t automatically include runtime type information is (probably) because the overhead of runtime type checking would outweigh the benefit when static type checking does a good enough job.
Also, JavaScript being a dynamic language has allowed some pretty complex patterns of types to emerge from real-world use cases that would be exhausting to enforce all the time at runtime. Typically in TypeScript, runtime type checking is (manually) done when the type system cannot otherwise confidently guarantee the type of a value. For example, it’s common to have a runtime check for the shape of a JSON api response because you’re not necessarily in control of what that will actually return. There are community supported packages to help make this easier [1].
0: https://www.typescriptlang.org/docs/handbook/advanced-types....
No, Typescript is very much just a static code analysis tool for JavaScript, there is no runtime at all, and there should not be one. It confuses a lot of people because they expect type guards at runtime, but it was never in the scope of the language to provide something like that.