The Telegram That Saved the World

January of 1917 was a tumultuous time, to say the least. America had not yet joined the war. Germany and its allies looked to be on a winning trajectory. The world was fraught with fear. Over in the…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Clean DOM queries in Typescript

Two very common minor annoyances in Typescript code that uses .querySelector() and .querySelectorAll()are often solved by explicitly type-casting with the as operator, e.g.:

This gets increasingly clumsy with .querySelectorAll() and arrays, etc.

First, if you know that your selector matches HTML elements, or specific elements types, you can use a type-argument:

This is much cleaner than explicitly type-casting with the as operator.

Secondly, you’ve probably noticed that the return-type of .querySelectorAll() isn’t an array — which is terribly unhandy when you want to for example filter or sort the elements. Here’s a really simple, type-safe way to convert query-results to arrays:

Looks a bit odd! It’s actually the spread operator ... which internally iterates over the query-result, and spreads the elements into the literal array created by the square brackets [] surrounding the expression.

You can then safely apply .filter() and .map() etc.

Of course, thanks to type-inference, the type-argument and spread operator also work together, and correctly infers types through to close arguments:

Neat! :-)

Add a comment

Related posts:

Downloading torrents via cloud services

You are the one downloading torrents to a computer’s storage using uTorrent or Vuze. Am I right? If so, you should definitely reassess your downloading strategy as the following cloud torrent service…

Dear santa I really did try to be a good Michigan girl but this mouth

Dear santa I really did try to be a good Michigan girl but this mouth. Buy here: Dear santa I really did try to be a good Michigan girl but this mouth shirt.

Jordan is where domestic and regional fissures collide

Former Crown Prince Hamzah bin Hussein has papered over a rare public dispute in the ruling Jordanian family in a move that is unlikely to resolve long-standing fissures in society and among the…