What's with all the one-letter types?
I'm enjoying typescript but having an issue understanding generics in some of d.ts files I'm using. I've noticed many use one letter to represent a type. When I write types, I use full one-or-two-word Pascal case as names and it works just fine. I was trying to interpret redux-thunk so redux's dispatch would play well, but the types are unclear to me. I feel like the concept of appropriate variable naming would apply here.
I imagine there's a reason to the madness. But what is it?
Posted Jan 11, 2019, 9:18 PM UTC
I think this is just a legacy computer science convention. Typically generic types are T, U, V... unless you have a better name for them. But even then, it's usually one letter.
In my code I often use longer generic names especially while I'm prototyping. Once I figure out the design, I might shorten them back to one letter for readability.
TSource and TResult are also common :)
So much more readable
When you say "for readability", do you mean readability for you or for other people? Do companies that use typescript and this style have a list to give while onboarding or are devs supposed to memorize them? It seems like so much cognitive overhead.
It depends entirely on the situation; there's no cut-and-dry answer. "I might shorten them back"
For example, if I simplified the type so that it only has a single generic parameter, and its role is obvious, then I might simplify it to
T.Tis immediately recognizable as the first generic parameter, since that gets ingrained over time during a computer science degree and job experience writing various languages.If there are multiple generic parameters and their roles aren't clear, I would probably stick to longer names.
And, where appropriate, I clarify within JSDoc.
To me, "for readability" always means "for other people" or "for my team specifically." I think that's software development common sense.
I understand the one-letter versions in some cases, such as P (props) and S (state) for React. It makes perfect sense because they are core concepts. But my "prettier" type defs are definitely not pretty because of the long type names, a disadvantage for sure.
Edit: I like the doc solution. That'll help me write them cleaner, at the least.
If it's not a generic, that just breaks my heart.
Correct for sure in making longer names. More descriptive is good. If something is TRUELY generic for any type T makes sense. Past that, be descriptive!