Ariel Weingarten

Ariel Weingarten

Scraping a 530 Member String Union Type

String literal union types are a useful tool for statically constraining string input. I had need of a Country Code type while building a Pwinty API wrapper. There are some handy gists already available with enums of the country codes, but I didn't need the full names.

This led me to Theodora, a site that had all 530 country codes. But how do we get the codes into our text editor? I popped open the developer tools and ran the following two lines:

var x = Array.from(document.querySelectorAll('table ul li')).map(n => n.innerText.slice(0,2))

I use Array.from because there are subtle differences between the NodeList type and regular JavaScript arrays. Nameley the lack of map function.

JSON.stringify(x)

I took that array, did a find replace on the commas and voila! A string literal union type for all the country codes. Available here in this gist.

Hopefully this technique can help you in the future!