TypeScript is terrible for library developers
erock.prose.sh
erock.prose.sh
I wrote a set of React components that gets 46,000 npm downloads a month and typescript is a godsend. My library is a bridge between two heavily popular projects, so my dependency tree is fairly intertwined. The library solves a real user problem and does it efficiently. It isn't totally perfect, but it covers 98% of the use cases.
I wrote comprehensive tests as I developed everything. I have good documentation. I have an example app people can play with. I have codesandboxes. Yes, it was a lot of work, but that's what building products is all about.
I've maintained this library for over 3 years now. I've upgraded it many times as the underlying dependencies have changed. A few times with backwards incompatible changes. I get outside contributors doing great work.
I do releases on a regular basis, without worry, because my test suite is that good and because I know that if the underlying types change, tsc will catch that too. These things have saved me countless hours of work finding bugs and fixing issues.
In other words, I call bullshit on this entire blog post. Ignore it. Typescript is the correct solution. What is the alternative? Just using JS and letting things break without knowing it? Come on.
Learn how to use types. Learn how to use a professional IDE, like IDEA, that shows you what's wrong as you develop. Learn how to write tests. Learn how to use a debugger. These are all things any decent developer should know and practice on a regular basis.
And if types change, and it still works, it's basically working by accident.
I don't consider that working.
If you write comprehensive unit tests for your javascript, that should effectively also work too... this is what ruby developers pretty much had to do.
We can see that over time based on the decline of ruby popularity in general, that fell out of style though. It is too easy to make a mistake and everyone was just duplicating what a compiler does for us.
I can't tell you how many hours I would sit there pair programming with other ruby developers just trying to figure out what 'type' an object is. Mind boggling, but it was good to get those high paid consulting hours.
And to be completely clear: you can have safe polymorphism without type hierarchies via things like type inference.
So the Liskov substitution principle now passes off as "working by accident"?
Whenever I find those guys on Github with several maintained multi-thousand star projects, I wonder "how do they do it?" (fund themselves + work on OSS). I am always curious about the underlying life stuff
Thanks in advance!
In this case, I needed the code for an internal project and decided that the company would benefit the most from making it a library and getting outside help on it. It was an itch that I knew many other people needed scratched because there was a competing project that had gone silent and was incomplete/poor quality. That justified my time spent... I had to write the code either way, might as well make it open.
When I look for people to hire, and I've done a lot of hiring over the years, I primarily look for people like myself who put that extra effort in. Either in their own personal projects or by at least contributing to something upstream. Even just simple documentation changes is something I'd hire over. I fully understand that people have lives outside of work, but honestly... if you're going to be a top developer, you've got to put in a top level of effort, because other people around you are.
In my experience, only about 20% are.
Surely that's not the only alternative.
Here's a few off the top of my head:
- Being able to write complex types in a syntax that more closely resembles JavaScript. Using Array length for counting or nested ternaries for if logic gets old fast.
- Being able to debug types, not console output, a real debugger. See: https://twitter.com/MarcJSchmidt/status/1539787500788613120
- More comprehensive documentation on writing advanced types
- A typescript specification
That is really nice. I'd love to see that live.
Yikes. This is how you end up in preprocessor hell. Macros are generally not a good thing. (Fyi: TS types are already Turing-complete which is arguably a mistake.)
> Being able to debug types, not console output
Eh. It's not like Java has a "type debugger." Why is this needed? Why are your types so complex? Weird ask.
> More comprehensive documentation on writing advanced types
Really beating the same drum here.
> A typescript specification
What does this mean? We have a pretty clear typescript spec[1].
[1] https://github.com/microsoft/TypeScript/blob/main/doc/spec-A...
Not suggesting macros, rather an alternative way to define types. A function that accepts and returns types. Seeing as typescript has a JavaScript interpreter I thought it might be feasible but I'm just spitballing it.
> Eh. It's not like Java has a "type debugger." Why is this needed? Why are your types so complex? Weird ask.
I don't buy this argument. Writing any type of complex types with recursion, arrays or ternaries sucks and it will take more than "this is how Java does it" to convince me otherwise. I like to debug with a debugger, not my head.
Take a look at the examples in the article to see some complex types and read some tweets from library authors complaining on twitter. I can find some examples if you're interested.
> We have a pretty clear typescript spec
I hadn't actually seen this and it looks interesting but seems pretty out of date, Typescript 1.8?
The article (and ensuing discussion) are about _library_ code, which necessarily has types that are orders of magnitude more complex than application code (source: see some of the links in the article).
The reason this isn't a problem in Java, C# etc is that the things these libraries do simply _aren't possible_ in the Java type system, so no one does them, and users end up with (usually) clunkier libraries.
Now there's definitely a question of when you start hitting diminishing returns but you can definitely do so much with and extract confidence from very strongly typed languages.
Really? This is fascinating, is there anywhere with more on this?
Are you somehow implying that C++ or Java don't have libraries? As a sidenote, React (and that entire ecosystem) is an architectural hellscape (see Vue for much more streamlined & cleaner code).
I'm also not necessarily saying this is a good or bad thing overall, since it can so easily lead to extra complexity.
FWIW, I'd choose C#/Rust/Kotlin/etc over TS 100% of the time for projects that don't need to run in a browser.
It seems like you and I read a different article. The post I read did not advocate for going back to JS; rather it advocated for better tooling and documentation (with examples, ideally) for library developers
Conclusion
I love typescript and think the team working on it are incredible. Typescript has completely changed the FE landscape and wouldn't want to dismiss its contributions.
But as a library developer, we need:
- better documentation,
- better tooling, and
- to spend less time making tsc happy.
I shouldn't have to read the typescript compiler source code in order to figure out why it's resolving a piece of my code to a specific type.
I developed a library used by the React app I work on to cache network results in localstorage (to reduce the number of expensive requests made on page refreshes) and generate React-Query query-functions to read the result from localStorage first before fetching from the network as a fallback (if the data is stale or uncached).It's not an especially large library, but I felt all of the pain points the author describes. It's great that you didn't with your library (and I'm sure there are large classes of libraries whose authors wouldn't feel these pain points), but it's a very real issue if your dealing heavily with generics, serialization/deserialization, and/or complex type interactions
I picked out this file pretty arbitrarily: https://github.com/TanStack/query/blob/main/packages/react-q...
The author of react-query seems to be very clear at communicating how the library works and the library itself provides a great developer experience, but it's also an example of how much work can go into correct typing in library code.
An example from the docs with middleware:
https://docs.pmnd.rs/zustand/typescript#middleware-that-chan...
If anyone calls this “easy, just learn generics” I won’t believe them further.
Typescript is a horrible as you make it.
Many of these things are easy to do in JS because JS wasn't built to be static typed object oriented language. Many of these are hard to type because the underlying language is so permissive.
As library authors the desire is to be as permissive as possible, to use the "simplicity" of the untyped JS language to express an API surface that accepts any combination of possible inputs and does the greatest amount of work with that. There are many "JS native" libraries that do that, including JQuery's $ "operator" that was a swiss army knife of a million different tasks all using a single constructor which created object instances that any number of plugins mutated over time. As a JQuery user that was a very easy experience to work with, it's permissivity felt like simplicity and easy-to-learn. As someone who briefly spent time debugging JQuery types definitions in Typescript, that was an incredible nightmare. (That was also many, many versions of Typescript back with fewer typing tools, many of which would have helped a lot, but also made everything even more complex than it was at the time.)
I do feel like a lot of library authors sometimes need to ask themselves as types grow more complicated in their libraries if the trade-offs are worth it. That "simple" API they are trying to give their users, is there a more "complicated" API with simpler types to use instead? Sometimes that's actually the simpler API to use understand too, but many of your end users see your types indirectly and simpler types in the API are simpler experiences of those types.
The article mentions needing to add lots of overloads and that's specifically something I'm thinking about there. Another example in this thread included a function that could take a set of arguments as either an object ({ a?: thing, b?: someOtherThing, c?: thirdThing }) or tuple ([a, b, c]: [thing, someOtherThing?, thirdThing?]) and in both cases many of the parts were optional, complicated further by the thing type being generic itself and the tuple accepting different orders of parameters. Can you just pick one, object or tuple for your API? Users have "less freedom" to do as they wish and the result seems less "simple", but you can eliminate so much complexity in your types. If you do still need both ways, maybe it's reasonable to split from "overloads" to different functions setThingsObject(things: { a?: thing, b?: someOtherThing, c?: thirdThing }) versus setThingsQuickly(things: [thing?, someOtherThing?, thirdThing? ]).
It's easy to armchair quarterback refactor other people's APIs, of course, but it's certainly a factor when I'm building my own APIs: These types are starting to get complicated here, should I refactor to simpler types? Should this API be split into two different/distinct endpoints to simplify the type signature? And so forth.
Some complexity is unavoidable, of course, but sometimes it is worth trading "simple, permissive JS with incredibly complex types" for "tedious explosion of JS that looks complex at first glance with incredibly simple types". It's a deep trade-off space to explore and what's right for any individual project is deeply personal opinion.
I think it really depends.
I get playing with technology for side projects, but for something commercial there is no way I would sign off on including that package into a project.
This is what types look like when you're on the library side. The post made very clear they aren't talking about the app dev side. The library types are complex like this so that the app devs have a smoother experience.
I really wish Typescript had a great pattern matching system. It would be very nice indeed for structural typing, everything would be easier to read, probably some ways to add more power/expressivity, etc.
eg
type GetOptions<T> =
// Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
T extends {
queryFnData: infer TQueryFnData
error?: infer TError
data: infer TData
}
? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
: T extends { queryFnData: infer TQueryFnData; error?: infer TError }
? UseQueryOptionsForUseQueries<TQueryFnData, TError>
: T extends { data: infer TData; error?: infer TError }
? UseQueryOptionsForUseQueries<unknown, TError, TData>
: // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]
T extends [infer TQueryFnData, infer TError, infer TData]
// ...
becomes type GetOptions<T> =
// Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
T extends match {
{ queryFnData: infer TQueryFnData, error?: infer TError, data: infer TData } => UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
{ queryFnData: infer TQueryFnData; error?: infer TError } => UseQueryOptionsForUseQueries<TQueryFnData, TError>,
{ data: infer TData; error?: infer TError } => UseQueryOptionsForUseQueries<unknown, TError, TData>,
[infer TQueryFnData, infer TError, infer TData] => UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
[infer TQueryFnData, infer TError] => UseQueryOptionsForUseQueries<TQueryFnData, TError>
// ...
}
or even, to make the top level way easy to understand in this case: type GetOptions<T> =
T extends match {
Part1 => Part1Match
Part2 => Part2Match
Part3 => Part3Match
}
where Part1Match etc are themselves pattern matches, so you can compose them like functions.The expressivity makes it possible for library authors have IntelliSense give more useful suggestions to the consumer, make automatic inference work in more places for the consumer, and make more illegal usage be impossible, at the expense of complicated type constructs. But of course all these is somewhat optional.
The entire article persecuted TS because the author wanted to learn quicker with little effort. Writing TypeScript in a node, app or library makes no difference. It is a language, NOT a framework.
I completely disagree, and I was surprised by this sort of comment.
Find me a single programming language whose docs are as good as TypeScript's docs and reference. I'd be surprised if you could come up with a single example.
I think you dismissed the actual issue he faced- gen type defaults, which I just looked is still not actually documented, it's just in the release notes.
Don't get me wrong, TS is my favorite language, but let's not gloss over things.
Recently learning rust (spare time) and c++ for work. The documentation for these 2 are awesome!
PostgreSQL has great docs too
I think we are better at writing docs for programming languages than we are at libraries and frameworks. Maybe because languages are more ‘fixed’ and less likely to change so over time they just get better and better.
It's a matter of having the skill and the will though, and I feel like a lot of projects simply don't emphasize documentation. Even so, not everyone's going to be a good technical writer.
Vue has excellent docs imo.
But in terms of technical writing being a skill. I agree. I appreciate the effort people put into docs. I try my best but I’m not very good. So I have a lot of respect for anyone who can sit and write excellent docs.
There are lots of ways to do things that you kind of just have to learn from reading blog posts, or reading code and then asking in the discord when you see something undocumented (because have you tried googling "what does <T=...> in Typescript mean"?).
Ideally, at the very least, all syntactic features and keywords of the language should be documented, but it's more than that; Typescript is a metalanguage, and authors of many libraries have also developed patterns which are essential for describing complex types. Some of these patterns are documented (for example, discriminating union), and some are not (for example, opaque types). And some features which are documented could do with a lot more exposition and functional examples ("as const"), or notes on when to avoid (enum).
Search “typescript generics syntax” and you get the excellent TypeScript docs on generics as the first result. It covers generic constraints.
Indeed, but I'm not sure how that's relevant since it doesn't cover generic parameter defaults.
Golang entire standard library is documented. Plus with how the language is designed docs don’t need to change with new versions. Just with new functions.
This is a non sequitur. Typescript can be bad even if other languages are worse.
The argument being made in the article and this discussion isn't "use X instead of Typescript" it's "Typescript should be improved".
The former is vacuously true once you know it is an option. Everything would be better if it could be improved.
The latter is subject to questions about cost. If Typescript had best in its class docs, that would imply that other communities had failed to find or execute a practical option to turn time/money into docs improvements. That would be moderately persuasive evidence that Typescript's resources are better spent elsewhere.
---------
On an object level: Django and the python community tend to have great docs.
Everything spelled out. No "you must read the whole thing or have worked with it for years to understand page 5".
Plenty of inline examples and even more user submitted ones (although as with all user generated content, some caution should be used when reading those).
But I am fairly certain that like the Perl documentation and unlike Java and Spring docs none of them was infuriating.
In fact, now that https://tanstack.com/query/v4/docs/plugins/persistQueryClien... appears to be stable I'm thinking it might even be good to migrate to this (though it appears to require multiple queryclients if you want different cache parameters)
I would even say: most libraries used for just about anything, are written in C/C++/Java, all of which are typed languages.
The post's author simply lacks the education and experience to actually have a valid opinion on this topic.
Besides your take being just outrageously exclusionary – the author is Eric Bower, a principal engineer who's also a Redux Saga maintainer. They're more than qualified to weigh in on this.
I’ve seen some crazy assed stuff they do with C++ templates and my reaction isn’t that they need to be spending their time on writing blog posts to explain the dark mysteries to me but that maybe I’m not the one who should be trying to write a library without spending a massive amount of time learning how this stuff works.
Sure, I can beat a template into submission using the famously helpful error messages the compiler provides and some random blog posts by people who actually understand what’s going on and I’m very thankful that they spent the time explaining it. Even having 1000 line long error messages helps once you learn what it is really complaining about. And this isn’t even my literal job, just something I do because I enjoy it.
IMO, the author could have done better by providing more concrete examples for the points of criticism, and understating the conclusion or moving it to the end or dropping it entirely, as I think it's better to give the reader the choice to make up his own mind, given the facts and evidence.
Just because I disagree with their premise (tool writers need to take responsibility for my lack of knowledge) doesn’t mean I think they can’t talk about it.
I mean, if they weren’t talking about it I’d have nothing to disagree with and have to do something productive.
And, you know, appeal to authority isn’t a valid counter argument…
The things the author talks about aren't even remotely possible in the type systems of pretty much any other mainstream language, so I don't know how you could interpret this as a "TS bad" post if you read past the headline.
"Lean how to use my types!"
Any given project uses a large number of libraries.
The point of a library is that it's 'useful'.
When a large number of libraries use vague and differing typings, it becomes impossible to manage.
The fragmentation created by the agile nature of Typescript is, predictably, a giant problem.
My point is that I've written a library that gets a lot of use. It has decent enough APIs. Nobody is writing blog posts like this about my stuff.
How? None of what you are talking about directly relates to the article. It feels like you are just reacting to the title and not the contents.
For instance, you say:
> I call bullshit on this entire blog post. Ignore it. Typescript is the correct solution. What is the alternative? Just using JS and letting things break without knowing it? Come on.
But the article says:
> I love typescript and think the team working on it are incredible. Typescript has completely changed the FE landscape and wouldn't want to dismiss its contributions.
> But as a library developer, we need:
> - better documentation,
> - better tooling, and
> - to spend less time making tsc happy.
This is not an article advocating for “just using JS and letting things break”, so why are you reacting as if it is?
Because the tone of the article seems to be that Typescript is horrible, and the tenor seems to be that the author is blaming his own incompetence on the language.
He has a point hidden in there somewhere, but I needed the HN comments to point it out to me.
Summarizing the sections:
- Documentation: there's docs on how to use the language as a whole, but nothing focused on writing libraries (how to build/publish, type tricks that libraries may need that apps don't, etc)
- Debugging: debugging types is a nightmare - you basically have to hover over temp variables to see what intermediate values are
- Complexity: TS types for real-world lib code can get complicated
- Testing: testing types is necessary, and the community has had to invent tools to help with that
- Maintenance: maintaining types and responding to issues takes up time
None of those are comments that "TS is horrible". Those are all straightforward concerns with the experience of writing and maintaining a TS-typed library, and as a Redux maintainer I can back up every single one of those. I actually did a talk on "Lessons from Maintaining TS Libraries" a few months ago, and I hit all of those points myself:
https://blog.isquaredsoftware.com/2022/05/presentations-ts-l...
> Documentation: there's docs on how to use the language as a whole, but nothing focused on writing libraries (how to build/publish, type tricks that libraries may need that apps don't, etc)
Why would there be? Building and publishing libraries is a npm thing, and has nothing whatsoever to do with Typescript. Type tricks that libraries may need? If you are going to write a section like that it’s pointless to write it about libraries in specific. There is nothing about building libraries in specific because Typescript isn’t about building libraries.
> Debugging: debugging types is a nightmare - you basically have to hover over temp variables to see what intermediate values are
Sort of, if you’ve managed to make your types complex enough that you cannot reason about them. But then again, I don’t know of any other language that feels the need to provide a type debugger. The fact that people working with Typescript think they need it is either testament to their competence, or the ridiculous constructions they make.
> Complexity: TS types for real-world lib code can get complicated
Well, yeah. But it’s exactly as complicated as you make it.
> Testing: testing types is necessary, and the community has had to invent tools to help with that
I don’t know of any other language that thinks testing types is necessary. The big issue in Typescript is that types don’t guarantee anything about runtime behavior.
> Maintenance: maintaining types and responding to issues takes up time
Well yes. Maintaining any library in any language takes time. Do people think this is unique to Typescript?
I guess my own point mainly comes down to no other language having any of these things, and the OP’s idea that it’s on the TS authors to provide it feels misplaced. It’s not core to the language, and a lot of the problems are self inflicted.
The blog post/slides were interesting though :)
Per the OP's article and my slides, there _are_ many aspects of maintaining a lib that are unique to TS above and beyond a plain JS lib, and it would be really helpful to have additional docs and tools available to help with our use cases.
Much of the complexity of TypeScript’s type system is a direct result of excessively dynamic interfaces in existing, untyped JavaScript. Starting with types is a good way to catch that early, rethink the interface, and either isolate it or avoid it entirely.
Damned if you do, damned if you don't.
However, if you look behind the curtains of these infamous gripes (some of them so often repeated they are cliché), 99% of the time its people who just haven't spent enough time around a certain framework or language and go create a rant post (similar to OPs post)
You're free to love the tools and languages you use all the time. But it's bad practice to go around bad mouthing tools and frameworks you don't full understand or haven't used productively.
I made a similar comment in 2019 about "TS pushes you towards simpler APIs" [0], so I agree that it's both a good thing in principle, and something TS usage leans towards in practice.
At the same time... JS _is_ a very dynamic language, library design reflects that, and library code by its very nature must account for the different ways that users will want to call it. That causes library types to be much more complex than app types.
[0] https://blog.isquaredsoftware.com/2019/11/blogged-answers-le...
I would argue it should not. If your API cannot be well expressed in the Typescript type system, it is your API that should change.
Especially since types are documentation. If you are using some meta dynamic type garbage, then I as a user of the API am left to wonder "Ok, this takes <U, K extends keyof U>... WTF is it expecting?"
This isn't to say that sort of thing is ALWAYS wrong, but rather it should be the exception and not the rule.
You do types because constraints make code clearer. By having a BF compiler in the middle of your template definition, you've defeated the types and you might as well put an `any` there with docs that say "here there be dragons!"
I think TS is great in certain cases- I love being able to get intellisense info from TS. When I download a new library and I get those helpful hints built right in from the libraries TS adoption, I love it. Typescript in this instance is reducing friction in my development workflow.
In my day job I work at an agency where we rapidly deliver a lot of new web properties. I have used Typescript on projects when it was a client requirement, but in our environment using Typescript generally feels like it overall adds friction and time to the project. Some team member inevitably gets stuck spending a bunch of extra time working with TS stuff: setting up the project with proper rules, writing some complex interface to deal with some random API we are either consuming or creating ourselves (in which case it is usually under rapid prototype development and needs to be updated constantly), etc.
I'm sure it is very helpful when working at scale with tons of developers on a highly stable and established project, but in my opinion it isn't generally applicable to every web property that it would be better on Typescript; it really depends on the scale of the project and the scale of the team maintaining it.
This sounds to me like MongoDB advocates like "psh! who needs a schema! don't slow me down, I'll just dump JSON into the database however I like." The types exist whether you write them down or not.
I agree with you that TS might not be great for everyone and every use case. But maybe you should just use `any` some more!
Yet in JavaScript I see this all the time - pass a string URL, but we also accept a function which will return a string URL, or maybe an option object - { url: string, strict: boolean }
So I think it's more of a culture thing.
For example: every object’s prototype chain ends with `Object.prototype`, so all objects have a `toString` function. I shouldn’t be forced to narrow my `number|bigint|string` (for example) just to do `x.toString()`. If I was, we’d get this ugly and bloated mess:
function callToString(x: number | bigint | string)
{
if (typeof x === "number")
x.toString();
else if (typeof x === "bigint")
x.toString();
else
x.toString();
}
Regardless, they’re just copying JavaScript’s duck typing feature. It’s not much different than languages like Java and C# that have interfaces. In C#, if my parameter is IClonable, I don’t care what it is, but know there’s a `Clone()` method attached to it. foo: int | strIn general, if someone with experience in a domain is complaining that something is hard, it's safe to assume that the thing is actually at least kind of hard, and that they aren't just a crybaby about indentation and formatting.
I also assert that if NDFrame.loc were less polymorphic (e.g. if you had a separate accessor like NDFrame.mask for boolean subsetting) it would be easier to use, easier to reason about, easier to teach, easier to document, and easier to write type hints for.
The worst situation is when you want to have multiple return types depending on the argument values, like Pandas' inplace=True. Putting aside the problem of dependent types, even supporting only literal True and False requires you to write out every single overload twice, creating a literal combinatorial explosion of overloads.
And that's also ignoring the whole world of parametric polymorphism required for higher-order functions, factory functions etc.
Maybe the situation is no better in something like C++, but I don't know enough C++ to have an opinion on it.
I’d argue that it has to do with C extensions making it a lot of work to get it right.
Some library code does it (which is where I learned how to do it ‘correctly’) but in general, run of the mill code it is pretty rare. Just something like an overloaded __add__ turns into a page and a half of code and there’s a lot of functions in the numbers protocol struct.
Labor of love really.
This is mostly an issue if you're tacking on those types on top of your existing design, rather than starting your design from your types, no?
Part of this hook is that users can pass in custom data. I tried to create a type that was basically "an object of any string key, with the type value". Gave up after like an hour of banging my head against my desk. Maybe I'm new to TS, but FFS it should not be that hard to do.
let x: {[key: string]: Type}
But maybe the documentation is lacking here? let x: Record<string, Type>
Pun intended.I’ll define 50 strongly typed constructs over having to run my code through 50 times to catch all the runtime bugs.
It accepts, as a parameter, a URL for Apple's REST API. My library handles authentication, and returns the parsed JSON result, with a handful of tweaks to make the API more usable in JavaScript.
Depending on which URL you request, you'll get different result object back. You could get a single object in response, or an array of objects, and the type of returned objects is different for each URL type.
How would you add TypeScript types to this API? Well, Apple provides an OpenAPI documentation of all of their URLs, which I could use to autogenerate types, but then, how would I handle all of those types in response to the user's string input?
Well, it turns out that TypeScript is so amazingly fancy that you can write very clever code to parse strings at compile time, extracting parameter types etc. from string literal types. https://lihautan.com/extract-parameters-type-from-string-lit...
The documentation explains how an API like this:
app.get('/purchase/[shopid]/[itemid]/args/[...args]')
can parse its parameters into a Request type with shopid, itemid, and args[] array parameters. This would catch a bug if you had a typo, e.g. "itmid".But the code to do that looks like this:
type IsParameter<Part> = Part extends `[${infer ParamName}]` ? ParamName : never;
type FilteredParts<Path> = Path extends `${infer PartA}/${infer PartB}`
? IsParameter<PartA> | FilteredParts<PartB>
: IsParameter<Path>;
type ParamValue<Key> = Key extends `...${infer Anything}` ? string[] : number;
type RemovePrefixDots<Key> = Key extends `...${infer Name}` ? Name : Key;
type Params<Path> = {
[Key in FilteredParts<Path> as RemovePrefixDots<Key>]: ParamValue<Key>;
};
type CallbackFn<Path> = (req: { params: Params<Path> }) => void;
function get<Path extends string>(path: Path, callback: CallbackFn<Path>) {
// TODO: implement
}
Nifty, eh? But, as the article says: how would you test this code? How would you debug it?Clearly, I wouldn't do that. Instead, I'd write a script to autogenerate individual methods, e.g. instead of get(`apps/${appId}`) that returns a parsed JSON blob, I'd autogenerate a getApp(appId) method that returns an App object.
But that API isn't any simpler than the API I already have; it's just different.
And let's not forget that I'd have to write a script to autogenerate these methods (or just their types) based on Apple's OpenAPI specification, and now I have to maintain that code, updating my @types/node-app-store-connect-api definition every time Apple introduces a new URL you can request. Testing and debugging that is a challenge in its own right.
And even if I did it, the complexity of my library just went from a few hundred lines of glue code to 1,000+ lines of type generation (plus tests for the generated types).
This is in no way worth it for me. As a library developer, adding TypeScript types would make my life harder.
I would say that the increased complexity of your project would accurately reflect the complexity of the underlying API
> As a library developer, adding TypeScript types would make my life harder.
Yes, but it would mean that the various parameters passed to your library would now be type safe, which sounds worth the work
That string-parsing thing isn't in TypeScript's documentation at all; it's a random blog post. I'm lucky I found it. TypeScript's site should document how to do this.
Furthermore, it should be easier to debug parsed stringly-typed APIs using the `infer` keyword. Today, I just run the compiler over and over again until it stops throwing errors, and the errors are really not very helpful.
There should be a standard tool to help me test that I used `infer` correctly, ideally helping me by fuzzing the code to see if I allowed something I shouldn't have allowed, or blocked something that I should have allowed, and to test against various versions of TypeScript.
Narrowing types shouldn't be done just by nesting ternary expressions. As the article notes, "It's pretty common in style guides to never nest ternaries. In typescript, that's the only way to narrow types based on other types. It's a mess!"
Lastly, this idea doesn't sit right with me:
> I would say that the increased complexity of your project would accurately reflect the complexity of the underlying API
I designed my library so it doesn't need to incorporate that complexity. Users of my API have to learn the API, but they can learn it from Apple, by reading Apple's documentation, and by inspecting the objects that Apple actually returns (rather than what their OpenAPI specification says they'll return).
Incorporating that complexity into my library will make my library harder to work with, more difficult for others to contribute to my library. As the article says, "Types make it much harder to maintain a js library, and especially difficult to contribute to them."
TypeScript is forcing me to duplicate the API's complexity in my code. Even if you think that "sounds worth the work," I think you have to agree that the work load is much higher than the work I've already done.
This paragraph kind of sums up both the OP and this whole HN discussion of it. So I'll throw my comment on here, although I suppose it could go pretty much anywhere.
Anyway, one way to read it all is: This just goes to show that
1) JavaScript sucks;
2) Therefore the whole world of "Web apps" built on it is an unmaintainable buggy nightmare;
3) Trying to graft "strong" (not really) typing on top of it in the shape of TypeScript is just polishing a turd.
It's like somewhere around 1995/2000 the world of computing jumped through a time warp back to 1975, and we've been stuck there, in a world dominated by the new BASIC, ever since.
___
Edit: Typo fix, *"domination" --> "dominated".
This sounds awful to me. Why wouldn't it be separate functions? I absolutely would not want that at all as an end user, I'd find it confusing and frustrating.
Furthermore, if Apple introduces a new function, I'd have to release a new version of my library to support it. Today, my library can handle any object Apple's API supports, without upgrading.
As it stands, the API works like this. It's fine.
const {data: app} = await read('apps/123456')
const {data: apps} = await read('apps')
const {data: [firstApp]} = await read('apps?limit=1')Had redux been developed in typescript from the start, I doubt it would have chosen this API. Then again, the current version is already in typescript, so perhaps that optimism is unwarranted; unfortunately my experience with it is years ago already.
This isn't part of the Redux core package, but it's a convention the community adopted shortly after Redux became popular. Redux Toolkit uses that as the standard structure for an action object. `createAction` defaults to just `{type, payload}`, but you can optionally provide a callback that adds the other `meta` and `error` fields. So yes, there's some additional complexity here because of the optional field contents, and this type is telling TS what the final type should look like based on which fields exist.
Note that as an end user, you normally don't even call `createAction` yourself - it's automatically called as part of our `createSlice` API. What end users normally write is:
export const counterSlice = createSlice({
name: 'counter',
// `createSlice` will infer the state type from the `initialState` argument
initialState,
reducers: {
increment: state => {
state.value += 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
// `action.payload` is now a `number`
state.value += action.payload
}
}
})How do library developers debug their highly dynamic and heavy use of conditional types, overloads?
Don’t do that. It dramatically increases compile time and results in a maintenance nightmare. Keep types primitive.
In my own code I use type unions of primitives and/or named types. For objects I use interfaces. With that I am able to provides types for about 98% of my code. That left over 2% is generally for extending the global Array type or extending an event.
Overloads exist in Typescript because as a language it needs to support what javascript supports - regardless of whether the pattern is "good". Overloads are heavily used in DefinitelyTyped because contributors there haven't had the luxury of designing the APIs they're typing. If you're designing your own API, you shouldn't be heavily using overloads because typed languages don't encourage the ridiculous trend of movable arguments that jQuery pioneered in the JS world.
Similarly, if you're writing all of your own code you shouldn't need type manipulation because you shouldn't be leaning heavily on variable mutation. Dogmatic stances on immutability are reasonably a matter of debate, but it's fairly uncontroversial to state that minimising mutation in your data flows helps prevent your code becoming an unmaintainable mess.
Etc.
[0]Writing good APIs is hard - bad APIs are inevitable. Typed languages make refactoring faster.
[1] Refactoring untyped languages is very hard and the tendency not to is deeply ingrained and very natural/reasonable.
What does type manipulation have to do with variable mutation? The main examples in the OP were of redux and related libraries, which use huge amounts of type manipulation but almost no mutation. I'm honestly not sure where the link between these two things would be, because to me they seem completely orthogonal.
After diving into the OPs linked examples, it appears that all they mean when they say "type manipulation" is just... generics.
Generics can be as simple or as convoluted as you write them. The linked examples certainly does look over-engineered: if you've got identifiers like `ActionCreatorForCaseReducerWithPrepare` in your library, you're entering into Java managermanager meme level of silliness there. That's not something you can blame Typescript for.
That some API doesn't conform to the abysmal ergonomics and astounding stupidity of most type systems isn't a problem with the API, but an endemic problem of modern type systems being dumb, weak, and hard-to-use. To an embarrassing extent, even most "advanced" type systems aren't super far from what came out of the 1970s. After writing ML-typed code for years, you learn the disappointingly primitive level of reasoning most textbook solvers can handle, and warp your code style ahead of time to that. Simpler calling conventions, all sorts of hints to inferencers, hacks around IO, etc. Language implementors know these systems have major issues in practice and thus tack layer after layer of weird special forms to handle what is "natural" in modern code. And then you get junior developers on a team, and have to pretend that this is all good and then hope they don't quit when they get byzantine type errors. And not tear your hair out when some library updates around these changes.
In a world where you can write 10 words of English and get synthesized a unique photorealistic image, or can sketch some code and get it autocompleted, maybe the problem is most type systems (still) suck. It's not inherent because we can manually reason about code & even run it -- and shifts to previously sacrilegious research like plugging in SMT solvers and neural networks has been changing historically conservative fundamental assumptions at a snails pace -- but that's where we are. So again, I wouldn't categorically blame the poor developers subjected to embarrassingly dumb solvers & UX's.
TS (probably) didnt have the luxury of thinking it out the necessary constraints and foundations for a top tier type system. Of course there were some bad choices like the XOR Union stuff mentioned elsewhere in this thread, but all of those make sense when you consider the type of code typically written in JS (before TS).
Typescript was probably never going to become popular if it tried to reach that ideal. But it provides way more safety bumpers for junior devs than JS previously had so regardless it’s a major step forward than whatever custom creation we used to hand each dev.
This isn't really true in the specific sense though (obviously it's inherently true in the general sense, but that's less relevant here).
Type systems are true & accurate representations of data structure and usage - any given actual human (a) may have an inaccurate mental representation of that at any given time, (b) that mental representation may change over time, (c) that mental representation will almost always be incomplete for any reasonably complex system.
Being "dumb" or intelligent isn't about representing data structures in memory, but the particular problem being discussed here is very much about that: in that context, humans are usually "dumber" than type systems.
Think linear regression vs neural networks, or in this case, ML-family type systems (with all the modern trimmings) vs an SMT solver. The "explaining your code to a three year old vs a professional colleague" comment is spot on.
Your comment may (or may not) be a reasonable criticism of designed-from-scratch languages, I don't really know for sure, but either way none of it applies whatsoever to Typescript.
Typescript is by definition an imperfect and over-complicated typed system because they have set themselves the task of levering typings onto a mature (i.e. "has legacy issues") language that was never designed with the intent of being typed.
It's even "worse" than similar cases like PHP, where after many versions the core devs have begun slowly implementing weak types on top of the previously-untyped language, because at least they have the luxury of being the core language devs and having the power to deprecate & change APIs if they choose. ECMA have no intent to type JS, nor to do anything explicitly to make life easier for the Typescript project.
Despite all the above, Typescript is brilliant because the unnecessary complexity is not layered, it's feature-based. Best-practice features of JS are easy to type in TS. If you're struggling with complex TS features, you're either writing a DefinitelyTyped package for a pre-existing project, or otherwise it's probably a strong hint that you're doing something wrong.
I know this because I struggle against these "pain during code design" & "get abstractions right" forces when I program.
Declaring types is really declaring what domain objects your program cares about and function signatures are really just describing interactions that can happen. So what 'domain objects' should meaningfully exist in my program and how do they interact? A bad abstraction can burn up a lot of time, so make sure you check your abstraction. I typically check mine describing stories to my friends (or rubber duck) and ensuring I'm using plain English and the other person doesn't get lost. YMMV
When you're doing web client programming you're typically using a library to accomplish work, and much of that work is reacting to user input and rendering data. I would argue that because so much of the linguistic heavy lifting has been done for web client programming, practicing the abstraction exercise is done less than in other programming domains. Doesn't mean it couldn't, just trying to highlight a difference in programmer domains. This is why the pain is more apparent in library programming than web client programming.
I imagine that advanced individuals in code design understand more of the connection between math and programming and are capable of describing systems of interesting work in few simple statements. I hope to reach those heights someday.
But I firmly disagree with how the article begins.
> In effect, we are shifting complexity from end-developers to library developers.
That is the whole point in creating a library. To hide complexity in a nice easy to use interface/API.
Documenting https://umbrellajs.com/documentation#addclass. The way I documented it is by opening with a code snippet with many of the possible options (which can also be combined!):
.addClass('name1')
.addClass('name1 name2 nameN')
.addClass('name1,name2,nameN')
.addClass('name1', 'name2', 'nameN')
.addClass(['name1', 'name2', 'nameN'])
.addClass(['name1', 'name2'], ['name3'], ['nameN'])
.addClass(function(node, i){ return 'name1'; })
.addClass(function(){ return 'name1'; }, function(){ return 'name2'; })
This is pretty easy to do in plain JS, and of course if you are writing code and using it you just read the first 1-4 lines and know what to do for 99% of the cases, while also noticing there's few "advanced/flexible" ways of using it. How would you even do that in TS?Then there's a classic initializer in JS that works like this:
function myLibrary(arg) {
if (!(this instanceof myLibrary)) {
return new myLibrary(arg);
}
...
}
This is very useful to create a library like jquery that you can initialize straight away without needing (but also being able to use) the `new` keyword, just calling it like a function and always ensures it returns an instance. To this day I haven't found a way of doing this in TS.Just make a static method that does initialization if needed and returns a new instance?
https://www.typescripttutorial.net/typescript-tutorial/types...
I'm trying to not be too hard on people as I read this thread, but it's baffling to me that web devs are getting filtered by features that have been in other languages since the 80's and 90's.
declare function addClass(...classes: (string | string[] | (() => string))[]): void;
It's pretty straightforward in Typescript. And when you go to implement it, tsc will make sure you cover all the types your function claims to support.> This is very useful to create a library like jquery that you can initialize straight away without needing (but also being able to use) the `new` keyword, just calling it like a function and always ensures it returns an instance.
Avoiding having to type "new" is not a very compelling reason to avoid Typescript, especially because Typescript won't let you make the mistake of calling the function without it. It's just not a problem.
Whether the effort is worth it is, however, a totally different question to whether it's possible.
In this example, I'm not sure why it's the functions responsibility to support all of these options when the user is perfectly capable of manipulating strings and arrays.
Different languages have a grain like wood does. And that subtly directs you by making some things ergonomic and some things difficult to express. I love typescript, but I definitely find it changes the resulting code.
Typescript makes "jQuery style" javascript much more awkward to write, because its harder to type. This is good and bad. I write less scrappy code in typescript - which I think makes it a worse language for quick prototyping. But the tradeoff is that I think its a better language for larger teams / longer lasting projects where functions are read a lot more than they're written.
The actual typescript answer for your API is "don't make your API look like that". Its not always the answer you're looking for.
* Only accept an array of strings. Not a single string, not several strings, not several arrays of strings, and certainly not a space/comma-separated list of classes.
* Add another single overload where you accept a function that takes two parameters. That function can ignore its parameters if it wants to, and it returns a list of strings, so you don't need to accept several.
You have the same functionality, it's not harder to use for an end-user, and it's infinitely simpler to type.
grid.selectRows(2) // index grid.selectRows([3,5]) // range grid.selectRows([[1,2],[4,6]]) // multiple ranges
It fits in the JavaScript spirit of "we will make it work" which I love.
Other major thing that made me decide to develop in es6 instead of typescript was compilation times. After a ctrl+s it had to compile ts to js for 10 seconds, which is annoying for me, as i like to check & test every minor code change.
Do you also use == and != for comparisons by default?
Typescript has a --watch mode that compiles as you work. Most test runners also often have a --watch mode. Test runners that support Typescript directly don't even need Typescript's --watch to be running as they'll do both, compile and test in a single step as you save. Anecdotally, the time it takes to run tests dwarfs any Typescript compile times and in a --watch mode of a test runner there's almost zero difference in the time it takes to watch ES2015+ tests or Typescript tests.
> .addClass(function(node, i) {return 'name1'})
^ what is node? What is i? Seems intuitive to think it must be a dom reference and an index. But in different domains it's not always gonna be so clear. Like I am not familiar with umbrella js, but maybe node could be a jquery object and not a plain dom ref? With typescript you can just say
type GetClassName = (node: HTMLElement, i: index) => string | string[]
// see how I added string[]. So I don't have to add yet another example
// of a function returning a string array instead of a string
and then add it to the union of types that can be passed into addClass. Great, no more guessing based on the domain knowledge I have (or don't), it's crystal clear. And it forces the lib developer to have the discipline to make it crystal clear, which they usually don't I'm afraid.
You use an ambient declaration to declare the missing classish part of the type.
declare function myLibrary(arg: Type): myLibrary;
declare class myLibrary {
member: Type;
constructor(arg: Type);
}
You see this pattern pretty often in DefinitelyTyped.I disagree with this. When working with rxjs I wanted to emit a single string in an error handler. Since strings are iterable I ended up with the characters being emitted.
The library authors added this "flexibility" (implicit conversion from values to observables) which caused a subtle bug that took me a while to figure out. A type error (expected observable, got string) would have prevented this.
For the other 99% of programming languages, that kind of interface makes the addClass implementation too complicated and forces unneeded branching into it. Consider: when the app developer is calling addClass, they _know_ which interface variation they're using. So they can easy write e.g. addClasses instead of addClass ... completely removing the branching from the code altogether.
Your input and output types are much simpler and static analysis is much easier as well.
> That is the whole point in creating a library. To hide complexity in a nice easy to use interface/API.
I think that's a fair point, but generating types that satisfy all use cases is very challenging to get right -- disproportionately so. I could see a world where -- without proper tooling and growing complexity -- typescript libraries becomes so difficult to maintain that people give up or burn out. Maybe that's a pessimistic outlook but I already feel that way some days.
If you write a library in TypeScript, determining what types are present as part of the interface is one of the very first thing that should be done.
Too broad a statement. There's loads of value in having a compiler figure out types for you after/when you write the code.
But granted, as a general rule you are correct. I was referring specifically to API interfaces.
If you're talking about figuring out what types you're going to accept, you should absolutely be defining that on your own up-front. If you don't even know what your types are how is an end user going to figure it out?
Totally agree. Minor ergonomic changes in a library have a wildly disproportionate impact on developers. If I save a developer 5 seconds with a better type, and I have 1000 developers using my library, that's 5,000 seconds I just saved - and that's assuming they only ever use my type a single time! With this in mind, I'm totally OK paying a tax on making libraries a bit harder to write, if it means that the benefits of stronger types fan out. After all, writing that type could take 4,995 seconds for me to write and still be a net positive.
And honestly, 5 seconds isn't even close to accurate. Good type definitions have saved me hours.
1. Keep writing code in a very dynamically typed style, despite choosing a statically typed language. Just deal with/stomach the extreme type complexity that is necessary to model your dynamic style statically
2. Keep writing code in a very dynamically typed style, and switch to a dynamically typed language
3. Stop writing code in a very dynamically typed style. If you’re using a statically typed language, write code that embraces static types
IMO 2 and 3 are both reasonable choices, but the author is deciding to choose 1, which is of course painful. I strongly disagree that libraries must be super dynamic though - that’s a pure style choice that some library authors adopt, but you can absolutely write basically any library in a static types friendly style, you just need to reflect that in your interfaces.
I guess the one thing that IS TS specific is that ppl can write their libs in JS, then try to add types to it, and if they chose crazy dynamic interfaces, it will be an incredible pain to statically type. But honestly, you could just say “this is a JS lib, there will be no TS types.”
Reminds me a lot of the NoSQL wars which eventually boiled down to 'Non-relational databases suck if you want to store highly relational data'. As ever, there are no silver bullets, only the right tools for certain jobs.
However, I think that saying it is "terrible for library developers" is a bit far. I think its terrible for developers who want to make use of advance types... which ultimately doesn't depend if you're a library dev at all.
It boils down to: "Typescript learning curve gets really steep after the basics"
The author mentions they help maintain redux-saga. I don't want to dig on them, but from my personal experience, that library takes you down quite an opinionated application path with complexity inherit to it. Heck, just making types for redux was a pain, let alone adding async and additional composability.
My take is that the author has chosen complex tech to work with, and that influences the complexity in their types.
TS is an excellent choice for a lib dev starting a new project today. I can see the advantages of using TS for the library code - in particular for a library that gets popular and welcomes contributions from other developers. However TS is a nightmare for someone like me who: 1. started writing the library 9 years ago; 2. has let the library get "quite" big; and 3. has only learned to use TS in the past year (for the day job) and is nowhere near to becoming a types expert.
I've had experience of people suggesting I rewrite the library in TS. Sometimes those suggestions have been quite 'evangelical' in their tone. As an (essentially) solo developer I just don't have the time, capacity or willingness to do that work - however much the end results might please others.
I also understand that having type definitions file for the library's interface is, nowadays, a critical factor if the lib dev wants others to use the library in their projects. But writing a .d.ts file for a large, mature repo to at least help those potential users can quickly turn into a World of Hurt. I know this because I've done that work[1] and I never want to do it again.
As much as I know that TS is a Force for Good in the JS coding world, there are days when I detest it!
[1] - link to the Scrawl-canvas .d.ts file on GitHub - https://github.com/KaliedaRik/Scrawl-canvas/blob/master/sour...
I did look at including JSDoc comments in the .js files to define types and function signatures, from which I could then autogenerate TS documentation files. But the results were a mess, and they ruined the existing documentation. Given that documenting the code in a way that allows me to autogenerate doc files (in a format that I like) is paramount, I abandoned that idea.
Also, the library's structure just doesn't sit well with my limited understanding of TS and TS definitions. I got the impression from the TS docs that the TS developers really like JS classes, and are not that keen on ES6 modules - which is unfortunate because my library makes heavy use of prototypes, modified by mixin functions.
So I hand-wrote a single definitions file in a way that matched as closely as possible the library's structure and preferences. Hopefully that file is enough to give developers some useful tips in their preferred IDE when they use the library in their projects. But I've only tested this in Sublime Text.
Or, worst-case, just weakening your types. Plenty of libraries have weaker types than they could have, but sometimes it's justified because it would be hard to get them exactly right
Sure it has a learning curve but I see highly flexible strictly typed as the medium-term future of pretty much all development as they provide invaluable safety nets for development, risk mitigation and productivity.
Large code bases without strong rigor,testing and/or static type analysis (eg. mypy/ts/flow) have no future and will not scale.
> The kind of hoops I have to jump through to get types "just right" in a web app versus a library is dramatically different. It's rare in a web app for me to need constructs like conditional types, type operators, and overloads. As a library developer, they are heavily used. These constructs are highly dynamic and embed logic into your types. This leads into my next frustration with typescript which is debugging.
I would have like to see some examples of "conditional types, type operators, and overloads" in action, and an argument for why these constructs are so much more prevalent in library code than in application code.
I don't have a counter-argument, and I don't have any reason to doubt the author's insight, but after reading the article I don't feel like I have an increased understanding of the problem-space.
Why are they more prevalent in library code: to make changes non-breaking (or breaking, but fixable with minor tweaks). Of course types can also be a solution to this problem, by promoting consequences of incompatible change from runtime to compile time, but that only holds if you can assume that all calling code is type checked.
Before judging it as "terrible" it would be good if author has more constructive criticism - if typescript is "terrible" what is not "terrible", haskell? What are specific things that can be changed to make it simpler? What if typescript is actually very good but the underlying type theory is just inherently complex?
You also have to appreciate what kind of value it brings to library users - and imho, in many cases, the value is so high that the whole discussion is a nobrainer.
In my opinion - if you want to use typescript, you need to learn it, especially when writing libraries. It doesn't make sense to want to use something and not want to learn it at the same time.
As the user of a library, not only do I hope for excellent documentation, but I also hope that the library authors have designed an ergonomic API that provides clear and consistent typings when using TypeScript. What I acknowledge I lack is a clear understanding of the level of effort that is required. Designing and building a library is challenging, creating documentation takes time, and support TypeScript types is another burden that I place on library authors.
Check out the article: https://liveloveapp.com/blog/2022-08-23-overcoming-typescrip...
- Denial - This should be pretty easy, just put types everywhere!
- Anger - But my code is correct! The damn compiler doesn't understand what I mean!
- Bargaining - Can't I just use any?
- Depression - This will take forever to figure out and I have a deadline :(
- Acceptance - It's a tool like any other, it's a hassle, most of the time is useless but sometimes it saves you from bugs and makes collaboration easier.
You just have to accept that the type specification in typescript is a whole separate language that you have to learn, that takes time to write correctly.
In my experience that's at least 30% more than writing js when you know what you are doing, more when you don't. Adding the linter and tests you end up spending more time on these correctness checks than actually writing code, and that is ok, or not, depending on the project goals.
When you are writing library code this cost goes up, WAY up because your library will be used in multiple ways by different people so you have a combinatorial explosion of cases that need to be handled.
I don't understand where this expectation that writing typescript should be as easy and quick as writing js.
IMHO the typescript docs are one of the best resources (just compare them to python docs...)
This is a disaster part of typescript that will doom you all. Through years and languages I made an observation, and it is:
If you give a way for smart people to create a horrible mess, they will internalize it eventually.
Sendmail.cf, template meatprogramming, #define hell, etc. Typescript “type manipulation” is one of these ways. It may seem very cool that you can define base types and then extend and reshape them in derivatives all you want. But types are not about solving puzzles in one go declaratively, they are about helping developers to understand which code may be incorrect. There is nothing wrong with declaring all the derivatives by copying type code and modifying it, because if there’s inconsistency, it will be caught later in tests, in interfaces, in your own code. Yes you create a dynamic structure of types, but it goes beyond human limits to understand or debug it.
One way to fix that is “type assertions”, based on the same principle. E.g. instead of declaring type B as a programmatic derivative of type A (and/or/with dozen of type metaprogramming routines), you just write B as it is and then assert that B maps to A as designed. Or make an IDE do this for you automatically. These assertions will still be hard to read, but the resulting type B will remain both understandable and correct.
Also, separately, please stop making polymorphic interfaces like “if you pass an object with key X after an object with key Y, that means mode of operation A, otherwise it’s mode B unless there is an array of numbers before the argument of type T, then it’s mode C”. They may look cool in readme.md, but are hard to remember and work with on both sides of an interface.
Like the author, I used the redux code heavily to figure out what I needed to do, but it changed often and it seemed like the authors were also discovering the best way to use it. Combine with a bunch of Facebookisms (they were literally called that inside Flowtype source!) that were half-baked and... yes, we were just doing trial and error to make our typedefs succeed.
Add onto that a severe weakness of Flowtype, its propensity to coerce to `any` without telling you, making your types green but masking real errors and... it was a time. A time with a pain quotient in the neighborhood of doing async module loaders in 2012, or cross-browser DOM manipulation in 2008. It seems, we always find a new problem to tickle our brains.
I don't think the `redux` core lib ever shipped any Flow types itself. Looking at the FlowTyped repo, I see community typedefs at https://github.com/flow-typed/flow-typed/tree/master/definit... , and the Git history suggests those were indeed written by community members.
(of course on the flip side, _I_ didn't even start learning TS myself until 2019, and goodness knows _that_ has been a lot of trial and error over time :) )
Generics are the worst offender, with people often using a single letter to represent something that's both hard to keep track of and impossible to intuitively make sense of.
Any type should be: `TUser` and not `User`.
Any generic should be: `<GPerson>` and not `<P>`.
Any interface should simply not exist because it's TypeScript, not InterfaceScript. The addition of classes into JavaScript was unnecessary sugar and they should just do away with it. So, `type` for everything, no more `interface`.
But that's a whole different subject.
I've also noticed that people over-engineer TypeScript. I had a team mate telling me he wanted to make URLs type-safe. I asked: "But why?" and he had no answer. There was no problem preceding it. There wasn't anyone asking for it. It wouldn't solve something we didn't know. It would just make the codebase more confusing to deal with because, in his solution, there wasn't a single place where routes were defined. Nope, routes would be inferred from Pages and their use of Page props.
It was genius. But it also was over 2000 (two THOUSAND) lines of code that I didn't feel like I wanted to deal with.
I gave him permission to publish it and get the open-source community involved. Once it's tried & tested over the course of many users and lots of time, we could consider it.
He wasn't happy. He was also not very pragmatic. TypeScript seems to do that to people. The "never any `any`"-crowd is so tiresome.
You sound like a sysadmin my friend! This is exactly how I feel about plenty of software that I've allowed into production, but that now keeps me up at night and distracts me from spending time with my kids.
One of the most useful things about plain JavaScript at this point is seeing if it causes genuine disgust. It's a razor for idealism versus pragmatism.
Weird. Classes are one of my favorite features, even before using TS. I do a lot of data modeling using functional techniques and the class keyword allows a really intuitive way of encapsulating things.
That is the whole reason to use libraries.
This blog post shows that types make development more enjoyable by shifting the complexity burden to library authors, who are vastly fewer in number than library users. It is a clear win.
I spend a decent amount of time in the redux world so `redux-toolkit` is a great library to see how types are done *correctly* in a real codebase. To be clear, they do a fantastic job with types, but the level of complexity is pretty startling.
https://github.com/reduxjs/redux-toolkit/blob/master/package...
That is just one example but the codebase is riddled with complex types. Also, when you look around, note the amount of types vs actual code.
It's pretty common in style guides to never nest ternaries. In typescript, that's the only way to narrow types based on other types. It's a mess!
Strongly typed shell, whatever works core.
In that vein, if anyone here can tell me how the hell you functionally map over a typed object by key in typescript I'll be eternally grateful.
I always wanna do something like Object.keys(typedObjName).map(...) but that doesn't work.
It's so stupid and small and minor and it's never really prevented me from getting something done but it drives me out of my mind that I still can't find any clear documentation on how to do it.
type TokenTable<T> = {
plus: T,
minus: T,
bang: T,
parenOpen: T,
//etc.
};
I also have a type defined as 'type TokenID = keyof TokenTable<unknown>;' this makes it possible to check if a string is a valid key at compile-time. The innermost loop of the lexer is a for..in loop. This gives you the keys of the object. One problem: if you try to apply the TokenID type to the loop variable, you get this message: "The left-hand side of a 'for...in' statement cannot use a type annotation." Because of the design of JavaScript, TS cannot give object keys any other type but 'string', even though this type seems like a clear match.To get the typechecking back on the keys, you either need to declare the loop variable outside of the loop itself, or use type casting like this:
let token = "";
let id: TokenID | undefined;
for (let key in patterns) {
const match = patterns[key as TokenID].exec(substring);
if (match && (match[0].length > token.length || key == "EOF")) {
token = match[0];
id = key as TokenID;
}
}
Neither is particularly clean.There's some boilerplate in the definition, but it's fairly clean and non-repetitive. And easy to use in the "client code".
https://www.typescriptlang.org/play?#code/KYOwrgtgBAKg9ga1AS...
const tokens = ['parenOpen', 'bang', 'plus', 'minus'] as const;
type Token = typeof tokens[number];
type TokenTable<T> = Record<Token, T> // alias for { [key in Token]: T }
const isToken = (t: string): t is Token => tokens.includes(t);
const patterns: TokenTable<RegExp> = { bang: /\+/, // rest }
https://jsfiddle.net/knvztxq7/ ^ that code will work, it outputs the key names to the console
https://jsfiddle.net/knvztxq7/1/ ^ that code... is also working even though I swear it hasn't worked for me before so now I think I'm actually just losing my mind.
Yeah wow I can't reproduce my error now... I'll come back here if I figure out what I did.
Is this a type space/value space thing? Like Object.keys(...) is always a string[] instead of Array<keyof TypedObj> like you might expect?
The majority of complaints I heard on Typescript were in the lines of: "I should be able to do this X thing that would not fly in a static language / not a good idea". Many times Typescript caught me doing stupid things like passing the wrong type or not checking data adequately, also forcing me to comment my code by describing shape of the data. It was a life saver for debugging, though it's not perfect, it's more like lipstick on a pig for a badly designed language.
> In effect, we are shifting complexity from end-developers to library developers.
Is this not why libraries are written in the first place?
Edit: I think their complaints apply to library development using any language with types e.g. complex C++ template foo is most useful for libraries? There is little in the article that is specifically a problem with TypeScript.
* Good autocompletion. Great for developers using a library. Somewhat self-documenting.
* Narrows down origin of errors. Great for library users and library developers. Nobody wants uncertainty or finger pointing.
* Typing is a strong API contract. Breaking changes to the API are more likely to break existing code. That is absolutely good from the library user’s point-of-view.
If a library developer wishes to deploy a highly dynamic API for their library, they can just use “any”, but expect most developers to dislike the library.
Planning your types correctly, and designing the API carefully to use types, does cost library developers a lot of time and thought. But the library users get outsized gains because library users usually hugely outnumber library developers.
> we are shifting complexity from end-developers to library developers. This places a huge burden on us to be experts with how typescript works.
That is to be expected. Good library code is hard to write. It would be lovely if there were better resources to help library writers, however it is a specialist role since library users usually strongly outnumber library writers.
It appears to me that many of the design decisions in TypeScript for the type system are there to help library developers. Patterns of usage were recognised and then added to the type system.
Disclaimer: not a TypeScript library developer.
If not, it sounds like one core issue is 'adding types to an existing untyped codebase is hard'. This checks out. :)
Imagine if every .so/dll/exe/obj/a file exported void* pointers as their inputs and outputs. That would be mayhem.
On our end, it enforces type safety better than the Google Closure Compiler. There has scarcely been a problem with type complexity that was not ultimately our fault. Just a couple minor things that TS amended later. For that matter the TS experience has only gotten better, generally.
On our users end, we can now give them a .d.ts file that's much richer and easier for us to produce to aid their autocompletion. And we can use that .d.ts file to ensure that all the methods we intended to expose/minify are getting exposed. The advantages with the .d.ts and documentation make it feel almost essential to me for library developers to consider TS.
TypeScript has only made debugging easier, much easier since it catches errors at time of typing unlike the closure compiler. The sole exception is that debugging is a bit slower since I have to transpile instead of just refreshing the browser. But I have tsc set to compile a relatively unminified version of the JS. But if the slowness gets to me, I can just edit the JS output until I solve the issue, and then carry those edits over to the TS. This has never felt like a problem, though maybe his library is significantly more complicated.
It is very possible that my opinions are colored by using the Google Closure Compiler for so many years for type enforcement, long before TS, which has forced a level of discipline that may be unusual to JS programmers. But it seems like the problems are not with TS, but with the labors of architecting coherent and consistent APIs. But I am not familiar with the author's work to really judge.
Feel free to ask me anything if you have questions about library design + TS.
Yes we need better tools as library authors but absorbing this complexity is our job. The more we take advantage of what Typescript can do the fewer types the end users deal with and the better experience they have.
Making your library's internals simple should be a non-goal. The number of people dealing with it will be a fraction of the people dealing with codebases using your library.
In my opinion, our industry is not generally exposed to type level programming or dependent types. As a result there are many popular APIs (redux, redux-toolkit, react, vue, jquery) that implement variadic and generic interfaces with many overlapping options on single functions. If the types for these interfaces had been written (or long considered) before being published then the authors' might have noticed how complicated they are at the outset and perhaps decided to solve the simpler problems first and build the complexity slowly.
"It is a poor workperson that blames her tools"
I like typescript but really worry that it's fueling a boom in unnecessary complexity and architecture. Are we going to look back at monster typescript codebases in the same way we look at monster java codebases riddled with abstract and redundant layers of complexity because the "design patterns" say to do it?
One interesting thing about Typescript is that it prefers .ts to .d.ts files.
So if you ship you .js, .js.map, .ts, and .d.ts files next to each other, your downstream consumers will be running expensive type inference on the .ts.
Instead, you have to manipulate package.json entries so that the .ts and the .d.ts are separate. (Or inline sources into source maps and exclude .ts from the package.)
Isn't that the whole point of libraries? Instead of having a hundred end-users trying to understand a library's untyped API, we save overall developer time by having just the one library developer type its API.
The amount of JS and TS out there is also a bit of a foot gun though so stick with heavily used/starred libs if you aren't sure.
One tool that helps a lot with developing libraries in typescript is TSDX[0] or its successor dts-cli[1] and there is a bunch of good stuff in awesesome-typescript[2].
Maybe library devving is harder?(more work?) with tyepscript but it is worth it for the end developer, especially if that end developer is you. If you aren't using your own libs then you're probably getting paid by someone else to make them or... idk.
[0] https://github.com/jaredpalmer/tsdx
Like for example, I wanted to type a generic object you can persist to a localStorage. What's the correct type?
Can't use an interface if you make a recursive type so you need a type. But if you use a Record<string | number, Persistable> and your client has some regular interface APIResponse { foo: string, bar: AnotherObject } the types dont match. I forget the specifics, but I ended up using { [key in string | number]?: PersistableValues } where PersistableValues includes all the primitives as well as arrays, sets, maps etc which I serialize/deserialize on persist and hydrate. Using `object` as type is listed as bad-practise in TS documentation which I agree but really, typing all the handled cases by hand is not fun either.
Wonder if I just should use any and throw an error if I encounter something I am unable to serialize.
This was basically me in a TypeScript React project, except that instead of being able to quickly iterate, instead I had to spend bunches of time messing around with types.
Of course, you could also say the exact same thing about using Java vs something like Python (though it has type hints available, of course; not that all codebases take advantage of it) and then have a discussion about what you think about strict type systems and where (front end/back end/DB) they're useful to have and in what capacity.
I guess it's one of those topics where thoughts differ, much like how some people might place a lot of emphasis on unit tests instead of integration tests, or even just (primarily) test the back end instead of bothering with front end tests, due to how much harder they can be to write, depending on the codebase.
If you find yourself thinking you need to test your types, you've taken a wrong turn somewhere.
I've always typed not only my types, but functions, programs, tests, everything, in every language I've ever coded in.
OK, sometimes I first write stuff (in pseudocode, or at least bad syntax) on paper first, but in the end I always type it into a code editor on the computer. Type type type, clickety click click clack...
It means that types are not subject to tests much like you don't test your tests.
types / tests are usually written in a denominational way and keeps the operational semantics of the program in check.
The Typescript itself, coupled with jest TDD made development very pleasant. The hardest part for me was figuring out how to publish the types so when a user installs it using yarn install, they get Intellisense. I think I did a poor job of it, as in the end I just published the source code. Even though I prefer when npm libraries do this ( as I can inspect the source in my editor easily ), I know the pros don't do that. If anyone wants to take a look and knows how to solve this type publishing, I'd be very appreciative.
Right now, your `dist` folder has `dist/index.d.ts` available, but `package.json` points to:
"types": "./lib/index.ts"
Just change that to: "types": "./dist/index.d.ts"this is exactly the point of a library in any language. The library authors do the heavy lifting precisely so that the end-users don't have to!
And again, this isn't my domain, but when I read stuff like > How do library developers debug their highly dynamic and heavy use of conditional types, overloads? or > Because types can be generated from other types and the highly dynamic nature of those types, there's a new class of tests that are required for any serious typescript project: testing your types. or > I spend more time tweaking types than I do writing library code. what I'm thinking is "Doctor, it hurts when I do this".
Interesting, I had never thought of this tension, but I think I disagree with the author and think this is a good tradeoff. We shouldn't assume all developers are library developers, most beginner developers for example don't write libraries or shouldn't. I think it's actually good to force competence in the library author domain (within reason), since they can abstract away this pesky complexity (the point of any good library).
I like this new mental model, but I still agree with the author that typescript is too hard to work with and developer experience with it has a ways to go.
That said...
I've learned that "library" types might not be the best way to talk about these concepts. What we're really talking about here are types that are complex/advanced enough to force you to venture beyond the primitive building blocs in the TS docs and into existing open source solutions that have trail-blazed more advanced use-cases. It took me only a few weeks to get comfortable with common TS, but at least a year to feel dangerous enough to write more advanced TS. I'm on year 3 now and I am still learning/forgetting so much about it.
I agree that: - Advanced types and their concepts are difficult to learn. - There is limited documentation on how to create/use them. - They can sometimes be difficult to reason about, mainly due to the limited syntax TS offers around advanced concepts.
On the the positive: - They can be learned with practice. - There is plenty of OSS out there to learn from - Once you learn them, you start to think differently about TS as a language instead of annotations
I wish there were better features/syntax support for: - Optional generics - Higher-order generics / Polymorphic generics (basically higher-order functions, but for types) - More built-ins (like ts-toolbelt, type-fest, etc)
I think this ramp of difficulty with advanced TS types is fine for the most part. Library authors have always carried way more of a burden than devs at the edge, even during runtime to ensure things like size, performance, flexibility, etc. TS is just another facet that is becoming more an expectation every day.
At the end of the day, a library dev gets to choose what level of investment they'll put into great types for their library. If they can pull it off, their tool will likely provide a measurably better developer experience.
That's my goal for my libraries, so choosing to go all-in on advanced TS is now a no-brainer.
Anywho, good luck!
For me, this should be a principle goal of someone writing a library. A primary function should be to shift complexity into the library, and allow other developers to not have to worry about it.
> I spend more time tweaking types [to gain confidence that my code is actually doing what it should] than I do writing library code[, which would probably be wrong, and saving time not having to write type-based tests].
I don't know what to say here; I've had types save me from a lot of blunders. If nothing else it moves my debugging/fixing time "left" in the timeline before it hits production. Maybe that prevents me from getting code out as quickly, maybe not since there are then that many tests I don't have to write.
Maybe he's just a way better dev than me too.
Don’t write that code because it’s impossible to debug and test? If typescript yields pain here, it’s appropriately felt imo.
What I hate is getting the build system set up to generate the right combination of .js/.d.ts files to work with the build system of whatever I'm using it in, particularly for libraries that use any form of preact/tsx files. I must be seriously missing something, but after 5 years as a node/react developer I still suck at making build pipelines for new projects.
To me types are very welcome. It's much easier to grok a function when I can see a type interface for it. Some libs do this better than others. Some libs have types as an after thought and you get confronted with something like:
``` export type Parameters = {[key: string]: any} ```
which is basically a giant FU and is as helpful as no type. But to me, well maintained type api is a great boon to both contributors and end developers.
Agreed that writing TS types for libs can be a pain. I actually did a talk recently on "Lessons Learned Maintaining TS Libraries" [0], where I talked about some of the techniques we used, and some possible TS changes that would be helpful for us as maintainers.
As one recent example, TS made a change in a 4.8 pre-alpha that broke RTK's `createSlice` types. Lenz tried to come up with a fix, couldn't, and had to add a workaround to check what TS version is being used and specifically use an altered type. Since there _isn't_ a good way to know what TS version is being used, Lenz resorted to hacking together a new package that abuses the `typesVersions` property to define a different TS type for _every_ TS major+minor version combo, and then used that to decide what the RTK type should look like conditionally [1].
Another pain point is debugging type transformations. I reworked the Reselect types in 4.1.x to do a much better job of inferring the argument types for the final selector, based on the intersection of all the input selector arguments. This ended up as a monstrous type that does a types-level map + transpose + intersection [2]. It took me weeks to get this working right, and I frequently had to break it down into multiple small intermediate types to see how TS was processing each step.
I know that someone on Twitter was recently working on an alternate TS type-checker based on bytecode, and they said they had some kind of a working types-level debugger [3]. Having something like that officially, where I could see each step of how TS was transforming the types, would be _hugely_ valuable.
There's a couple folks like AndaristRake who are able to dig into the internals of the TS compiler itself to trace how it's interpreting the types. I definitely don't have that ability :)
[0] https://blog.isquaredsoftware.com/2022/05/presentations-ts-l...
[1] https://github.com/reduxjs/redux-toolkit/pull/2547
[2] https://github.com/reduxjs/reselect/blob/v4.1.5/src/types.ts...
[3] https://twitter.com/MarcJSchmidt/status/1539787500788613120
Also, debugging type differences with deeply nested objects (like what happens with graphql schemas) can be hugely painful. You need to copy the error message to its own file (since the errors can be huge) and debug what specific piece failed.
I do feel the Typescript documentation is lacking and the only way to get better is to read open source projects to see how others have done it… which is only helpful when they’ve solved the exact problem you’re looking for.
It’d be great to have a recipe book of common advanced typescript manipulations and how to compose them together.
Right, this happens in any language where you are writing type lambdas or functions at type level, which makes sense actually. We've been doing this in C++ as well for years...
On another note, Redux is fundamentally a bad experience in typescript because the action type must extend from `AnyAction`, so it poisons the well.
What we need is a first-class typescript state container with a rigid API, even better would be first-class enums and pattern matching...
Writing generators isn't fun in typescript, so yes I imagine redux-saga would be painful.
Here's all you need to do as a typical Redux app developer to get started using Redux Toolkit with TypeScript:
- https://redux.js.org/tutorials/typescript-quick-start
Note that we specifically tell you to use a `PayloadAction<MyPayloadHere>` type, which results in well-typed reducers and automatically generates strongly-typed action creators to match.
If you're using Redux at all, you _should_ be using Redux Toolkit to write your Redux logic.
First, and most related to TypeScript, is that the library predates TypeScript and the dynamic nature of JS made it easy to create much too complex interfaces.
Second is when a library is very frameworky rather than a less opinionated library (I see this sometimes in Sorbet types written by my colleagues, even for greenfield stuff).
Don’t want to make a value judgement on either, but it’s certainly possible to write useful libraries with simple types. Look at golang.
Library developers obviously deserve nice things too, but that is why they should be getting paid for their work. If TypeScript is better for users(I think it is, although I would prefer we move the whole world to Dart natively with no compile step....), then it helps you make a better product.
Which you should be getting paid for, as many FOSS devs are.
I have no idea what this means. What are "tools for a library developer"?
> I think the underlying assumption here is that there is no difference between a library developer and an end-developer, which I reject.
Expansion on why they reject this would be of interest here. I'm a library developer - I'm not aware of any differences.
There is - developing good libraries requires a much higher standard than developing good frontends.
> In effect, we are shifting complexity from end-developers to library developers. This places a huge burden on us to be experts with how typescript works.
That is the main purpose of libraries: to take work away from the user of it.
So I have the opposite problem: as a library user, JavaScript is terrible for me, because even when I use TypeScript I get runtime type errors from bad type declarations or even just holes in the TypeScript type system.
I don't get the point at all of the difference between app and library developpers. Any app of non trivial size will have some kind of internal library and thus any app developer is a library developper too.
As a library author myself I struggled a lot more with monorepo management and changelogs/publishing but tools like turbo/nx/changesets have really helped here.
Also, I've never had to use conditional types in my life. I think you're over-complicating things.
I really wish there was a kind of type builder where I can use ifs and switches to build complex types. For me that would already take away a lot of the pain of maintaining and writing complex types.
Yes. The point of making a library is almost entirely to take the complexity load from developers.
All these complex (albeit well-defined) interfaces add friction between libraries.
Imagine that you're an electrician and your job is to change a lightbulb... Do you really want to have a meeting with the central standards committee and the lightbulb manufacturer in order to be able to change that lightculb or you just want to screw it in and be done with it?
The core problem with these type systems is that they try to create a globally-consistent universe where all the different modules/libraries agree about what all the different types which might exist in the actual universe are but somehow they never manage to get there; or if they get close, they end up extremely rigid and require a lot more effort to maintain (E.g. Java).
As my co-maintainer Lenz Weber just said on Twitter:
> No other language I know allows us library authors to have that much influence on autocomplete and dev experience. We could all just ship mediocre types with some added runtime exceptions, like we are forced to do in other languages - but we see this opportunity and we go for it. We are not forced to do that, it's the same masochistic drive that makes us write the lib in the first place.
We've deliberately done a lot of work internally to make sure that our end users _don't_ have to write very complex types in their app code.
As I mentioned in another comment, the linked `createAction` example is specifically representing an object that looks like `{type: string, payload?, meta?, error?}`, and strongly typing the possible combinations of which fields exist.
The net result here is that depending on how you've defined your reducer and action, when you type `action.` in the editor, you'll get correct autocomplete listing exactly which fields _do_ exist based on this specific action type.
Normal app code won't have to write anything like those types.
ActionWithPayloadAndError createAction(String, Payload, Error)
If I understand correctly, overloading doesn’t exist in TS.
> This places a huge burden on us to be experts with how typescript works.
Yes, exactly. That's how it is supposed to be. You need to have expertise in the programming language to be able to effectively develop libraries other developers will use.
The author also mentions:
> In effect, we are shifting complexity from end-developers to library developers.
This is not a valid complaint. This is obvious and self-evident; and also true for any lib developer in any language - you can't avoid it. Libraries exist to abstract away complex logic so those devs consuming the library don't have to worry about writing their own implementation - an app can delegate functionality to a library and this has the benefit of reducing the app's maintenance burden and speed up dev time by re-using another developer's work. And for lib devs, this inevitably requires they spend effort to make their library easier to use.
Breaking changes are introduced way too often and the compiler can't output backwards-compatible types.
While Javascript has nothing to do with Java, the same cannot be said for Typescript and types...
Maybe a language with better type guarantees would be better suited for library developers; but if the alternative is plain javascript, then no. Just no.
[1] https://hirrolot.github.io/posts/why-static-languages-suffer...
> There's great documentation and blogs for end-developers but there's very little for library-developers
Because there isn't a difference. I write my applications the same way that I write libraries. TypeScript gives you the flexibility to do that as well. If you want to use looser types in your apps and in your libraries, go right ahead. Some people may want more accurate types coming from your library. They'll either improve them or pick something else. You aren't required to appease them. I know that you stated that you reject this notion but just now I was working on a relatively straightforward React app and I've got a number of places where I'm doing slightly more advanced types. If you aren't, you're probably leaning on library developers to do that for you which is fine but that's a choice.
> How do library developers debug their highly dynamic and heavy use of conditional types, overloads?
I literally just make a number of assignments and hover over the types to verify that they look right. There are better ways of testing these that I'll get to later.
// Hovering over this will either show what I want or not
type ComplexFoo = ToComplexType<Foo>
Sometimes those types might look nasty and be difficult to parse so there are ways to force TS to simplify them for inspection. There are even libraries[1] that help with that.> I spend a decent amount of time in the redux world so redux-toolkit is a great library to see how types are done
Redux is an inherently very dynamic system. It's dynamic by design. Capturing all of that dynamism in a strict system is _hard._ `redux-toolkit` and related codebases are not representative of the normal struggles for library developers. Additionally, see point 1 about how you can choose how good your types are. It would be technically correct for `createAction` to just return
interface Action {
type: string
payload: unknown
}
They choose to make their types better so that developers don't have to carry that burden.> It's pretty common in style guides to never nest ternaries. In typescript, that's the only way to narrow types based on other types
I'm always open to syntactic improvements. If someone finds a way to make the type syntax simpler without conflicting with existing JS syntax then I will be very happy. That being said, the syntax isn't so inscrutable as to be unusable. It just takes some getting used to.
> It's not enough to test your types against the latest version of the typescript compiler either, you also need to test against previous versions
I disagree. The TypeScript team does a very good job of keeping things backwards compatible. In the rare case that they don't, your library is welcome to state that they only support certain versions of TypeScript. This is a pretty standard problem with any sort of dependency. Nothing about TypeScript makes this particularly difficult. If you are going the extra mile to check multiple versions of TypeScript then you're awesome.
> This new class of tests are in their infancy and there's a baron wasteland of tools that are now deprecated or partially maintained
My opinion: a lot of these tools become unmaintained because they aren't necessary. Testing types is pretty easy. Include these two functions and you're golden.
function generateType<TReturn>(): TReturn {
return null as unknown as TReturn
}
function assertType<TExpected>(value: TExpected) {}
Then testing your types is as simple as assertType<Expected>(generateType<ComplexThing<number>>)
> When first attempting to contribute to a project, one must grok the application logic as well as the type logic.If you're running in to this then those people are doing it wrong. Types should make impossible states impossible and do their best to make the application logic the only thing that is possible. If you understand the application logic, you understand the type logic. They're one and the same.
> I shouldn't have to read the typescript compiler source code in order to figure out why it's resolving a piece of my code to a specific type.
You shouldn't and you don't. Better documentation is always better though and I agree that more in-depth first-party documentation would be great.
[1]: https://millsp.github.io/ts-toolbelt/modules/any_compute.htm...
that is the exact reason why I use external libraries.
I feel i spent more time with that than with the development of the code ;-)
It's a fucking boring topic that has been done to death since 2012. Get this deleted guys.
The comments in this thread say that the way you are writing TypeScript is wrong. What they are advocating for is essentially turning TypeScript into Java in terms of its style. This is what good TypeScript codebases end up looking like. They don't look like JavaScript. You could take all of the type information out and they still wouldn't look like JavaScript.
I think that when people find that their ex-JavaScript, now TypeScript codebases have become Java codebases, many of them will realise they don't really like TypeScript anymore. If they are the people that said "You aren't professional if you don't use TypeScript", etc, then they are not welcome back into the JavaScript cult. If they are not one of those people, they must profess their hatred of TypeScript, and then we will let them back in.
Anyway, no matter what, you still have to work with the native APIs and so on, which just don't work with TypeScript. Take Web Components for example. You create a web component by defining a class, but you never instantiate the class yourself. You use document.createElement('my-component'). Good luck typing that. Good luck typing proxies.
I hate TypeScript.