⚠️ This is a bit of a rant as I've lost patience with TypeScript and I need to vent.
While converting a medium sized Nuxt application (~15 pages, ...
For further actions, you may consider blocking this person and/or reporting abuse
Types you don't care about are unknown
Use typeof type operator and ReturnType to generate the type for you.
Other than that it's just the "cost of doing business". Those interfaces had no idea that you would be adding your plugin. So now you are merging your plugin into those existing interfaces.
Also it's not duplication. There is type declaration space and variable declaration space or as I like to put it:
The
makeAPI
function is pure JavaScript and lives in value space. With the helptypeof
andReturnType
we pulledAPI
into type space for compile time type checking. Monkey patching those interfaces happens at runtime in value space, so TypeScript can't really track where it is going to end up - yet value space code is going to try to access it in those places so it becomes necessary to tell TypeScript where it is going to show up.TypeScript is a compile time static type checker. Here you are assembling an object dynamically at runtime (in value space). TypeScript hates that - so you have to take TypeScript by the hand and explain to it like it's five.
The big help here is
Partial<URLBuilder>
because it makes all the members of the object optional so things can be added piece by piece. However for methods we have to assert thatthis
will be a full blownURLBuilder
by the time the method runs.In the end you as the developer have to take the responsibility of asserting that you are sure that
builder
is no longerPartial
but a fullblownURLBuilder
.Love this reply.
Top notch.👏👏👏
Wow, wow, wow. Lots of useful advanced stuff here 🤩
Super useful comment.
Sorry to say but yes it's you. Typescript is a superset of js so you could just rename the files, turn down the strict mess of your linter and incrementally turn your codebase into more of a proper ts codebase.
Some of the challenges you write about can be solved with a simple Google search.
Using anonymous types really doesn't help. Your compact issue for example, and the url builder return type (which is missing, btw).
It's a little bit of time invested now, but easily recouped by preventing bugs before they occur while writing code in the future. I've upgraded a large corp application and it was a pain as well, but well worth it. Using a good ide like webstorm can take some of the tedious work out of your hands, so is highly recommendable
You mention that while upgrading a large application code-base, it was worth it. Could you give a few examples of what are the best, real life, advantages ?
Also, I'm using Webstorm. I'm greatly in love with it and it surely helped a lot.
I was using Jetbrains IDEs as well in the past but nowadays I need to say that VSCode is the top tier IDE for many languages.
The first day was hard to me due to keybindings so I added a pluggin called intelliJ Idea Keybindings, edited the comment block one (I'm with a TKL keyboard) and I'm happy since then 😆
It consumes way less RAM and CPU, has built-in features while working with JS that webstorm lacks, it's more customizable and so on.
After working with both we ended up with a middle point solution that has become our favourite, and it's using TS + JS but not in separate files, let me explain:
You can just add TS Pragma at the top of your JS files
// @ts-check
Then declare the types you want with JSDoc
Quick example:
If something bothers you (let's add an example):
It will complain about
Type 'string' is not assignable to type 'Dialect'.ts(2322)
in the dialect option.Do I really need to create a Dialect for that when a string stored in a config/env file will do the exact same job?
I mean, I'm not going to suddenly use a different dialect on the DB, it will be the same always for this project and if I need to change something its just about editing the config/env file, migrate the models, migrate the current data... it's not something you do "by mistake" or whatever, you really need to invest time on it.
Moreover I'm not working with POO which means no custom classes are (nor will be) added to the project.
Quick fix:
This way (using TS pragma + JSDoc) you will
It's a win-win, the best of both worlds and (to me) the way to go..
We already tried it in a big project that is in production since 5 to 6 months ago (at the time of writing that).
We had 2 webapps, one with JS another one using TS and this third one using the approach described in this comment.
Now, no one in the team wants TS anymore, that was unexpected at the beginning but we're getting faster development times, the code is much more understandable by anyone new in the project, no flaws due to types, makes PR review easier and so on.
We're thinking to migrate the TS one to this approach first while adding this approach in the JS one anytime we need to edit a file, find a bug, add a feature and so on.
Thoughts on that? Have you ever tried this approach?
I love JSDoc and use it everywhere I can. In a personal project I use JSDoc to output types for users to consume. This is a good tradeoff for me, because I don't have to bother with TS, but my users can have their types if they need to.
I'll try your method, but I'm worry I won't like putting
@ts-ignore
everywhere.You just need to discern wherher is something verbose/unnecessary/absurd or something useful that must be provided 😂
I cursed a lot when I started to use typescript as well. I felt as if someone tied rocks to my hands when I was able to write perfectly working JS before.
Soon you will adapt and naturally write code that gets along easier with TS. This is not exactly a drawback. Maybe it gets less elegant here and there, but its mostly for the better, trust me. Where you are, I have been - where I am, you will be :D
I don't have time to go into every single of your examples, but at least the first two:
TSC does a lot of code checking but it has its limits. It does not know that when you call
localStorage.getItem(key)
, the key HAS to be present because its derived from the current keys in localStorage. To mitigate this, you can give the TSC a hint that a given value WILL be there by adding an exclamation mark:JSON.parse(localStorage.getItem(key)!)
This is somewhat the same problem:
TSC sees: "ah, he assigned a string here" and internally derives the type of "options" to
{notation: string, maximumFractionDigits: number}
. He is not exactly incorrect here. Butstring
does not match the options wanted for NumberFormat. So what you need to do is:As stated 2 times, I know this is mostly due to a lack of knowledge. So thanks a lot for the encouragements. I'm fully aware that a project with 80K stars and 33K commits over 650 contributors is not a failure.
Also, thanks for the two advices. BTW, @ryands17 taught me that
Intl.NumberFormatOptions
is an existing type.An easier way to do this is
The "const assertion" will concrete the value to "compact" instead of string
Edit: oops, someone already mentioned that, sorry.
You should specify that
notation
not just thestring
type but concrete typeIntl.NumberFormatOptions['notation']
Having to convert a project is always a headache no matter what it is to what it will be. I have been recommending to customers to make a new major version and port to typescript scaffolding from scratch with typescript and slotting in the core bits to suit.
I haven't used Nuxt, but the first two can be simply done as follows:
Using the string
'null'
as a backup like this: PlaygroundUsing the exact type of what it expects: Playground or directly pass it in the function instead of declaring a new variable.
I suggest you trust your own reasoning and intuition more. TS is cool and all but it is not the silver bullet that the dogmatic part of its community makes it out to be. Most importantly it does not come without tradeoffs or costs (like everthing else). For some projects and some programmers the benefits are larger than the costs but it is not always the case. Should you learn it? By all means yes. Should you use it? When it's appropriate. Should you adopt a victim mentality and worship at its feet? No way sir.
Maybe you should ! Come suffer with me ;)
Thanks a lot for taking the time to address every points. I really want to understand why so many are enthralled by TS. Be sure that on monday, I'll be going back to this with your help.
I don't want to go into all of your issues. So I stop at the first one since no one mentioned this:
Solves your problem here. By default, TS makes / types these objects loosely, as such at it sees
which makes sense as nothing prevents you to write
options.notation = 'foo'
. I think you fall into the trap of thinking thatconst
means immutable, but it rather means "cannot be reassigned".The alternative to help TypeScript here with the
as const
is to just tell it the right interface in the assignment.Nothing wrong with learning.
Would not recommend to use the localStorage object like that in Typescript or plain Javascript. How can you be sure you want all the items stored on localstorage or that they will be JSON parsable? It's better to keep a list of localstorage keys for your app somewhere and loop through that, instead of all the keys on the localstorage object.
For your string literals, try this:
Your code duplication issue I'm not too familiar with Nuxt. Do they have Typescript documentation? If so, they'll usually explain how you're supposed to extend the built in interfaces.
No idea what you're trying to do with that URLBuilder =P
I don't think there's a hype around Typescript, but it is slowly growing because people appreciate type safety (or they learn to) and not having as many runtime errors.
I also think that TS takes the fun out of using JS.
Metaphorically, pure JS is a high-wire act without a safety net to catch you when you fall. Thrilling when you succeed. Possibly fatal when you don't.
Since I've mastered JS, I full well know which types of acrobatic stunts are the most dangerous. I code special scaffolding for those tricks, but prefer to stay high-flying without a safety net for all the easy stuff.
Nuxt is very painful when it comes to declaring global types for inject, store, global pipes and prototype extensions. Unfortunately there is also no way to make that easier, as is the nature of vue. That is one of the reasons why I ditched Nuxt for Next.
I'm a bit late to this party, but thought I'd have something to add.
Edit: on reflection my first point is a bit pedantic. I've tried to get 2 browser tabs to interfere in such a localStorage loop, but have so far been unable. It would seem localStorage synchronization happens asynchronously. One could make the very valid argument that during a debug you could change any value to anything, so bringing that up in regards to type safety is moot.
On localStorage: your statement "Even worse, I can't have unset values because I'm looping over existing items in the localStorage." is false.
Will log
"b"
andnull
. While I would agree this is pedantic another situation this could occur is when you have one tab clearing localStorage entries whileforEach
is running in a second tab. Since the localStorage is shared between tabs it'd be allowed for your browser to process them simultaneously.I would agree I'm being pedantic here, but what you're asking of Typescript is actually quite advanced. It would have to type narrow
localStorage
to aRecord<K extends string, string>
and letkey
be ofK
whilst understanding thatforEach
will preserve that narrowing. Typescript's flow analysis can't deal with lambdas very well, since it doesn't understand (yet?) that the lambda inforEach
is synchronous and that callingforEach
doesn't change any type narrowing. This would have to be a whole new Typescript feature to indicate that a function calls one or more lambda's synchronously (and maybe even in a given order) and it doesn't have any side effects that could change any type.Luckily the fix is very simple:
This bypasses all your issues by having a single expression
Object.entries(localStorage)
contain both the keys and the values, then Typescript can work with the type of that expression and it doesn't have to understand the exact workings offorEach
andlocalStorage
As for your dynamic interface: you are trying to get a static type checker to understand your dynamic interface. Hardship is to be anticipated. My suggestion would be as follows:
Basically this would drop the dynamic part of it at the cost of some minor duplication.
This also solves the issue of changing the
builder
value. As soon as you have a variable declaration in Typescript, it assign a type to that variable based on the declaration. If you later change a structural bit of that variable, Typescript needs help figuring it out. In general typing is easier with immutable values as they can't, by definition, change their type. If you must have it dynamic I'd suggest this solution at the cost of one type castYou know you can adjust and manually relax eslint rules, some to warnings, others to off. Like the rules for implicit any.
Also casting types is good, like if you got the JSON.parse example, cast all your local storage.get() as string
I wouldn't use inject: (name: string, plugin: any) => void
It's even possible to just use
checkjs
and not use any Typescript files that's the bear 🐻 minimum.Many of the points discussed find their roots in bad code design. Unfortunately, yes it's you. TypeScript is fine.
See studies >
dl.acm.org/doi/10.1145/2384616.238...
dl.acm.org/doi/10.1145/2635868.263...