Code Snippets
Here are some code snippets you might find useful. I leave them there when they don't deserve a library on their own.
You can find more on my Twitter account.
Copy-paste at will, everything here is free to use (licensed under MIT).
URL query string from object#
TypeScript Browser Node.js
Create a URL with escaped query string arguments from an object, without any dependencies:
export function url(base: string, args: object): string {
const url = new URL(base)
Object.entries(args).forEach(([key, value]) => {
url.searchParams.set(key, value)
})
return url.toString()
}
// Example usage:
url('https://accounts.spotify.com/authorize', {
client_id: process.env.SPOTIFY_CLIENT_ID,
redirect_uri: 'http://localhost:12345',
response_type: 'token'
})
// -> https://accounts.spotify.com/authorize?client_id=foobar&redirect_uri=http%3A%2F%2Flocalhost%3A12345&response_type=token
Browser support for URLSearchParams
(used in url.searchParams
):
Interface type filtering#
TypeScript Metaprogramming
Get the keys of an object for which the value is of a given type:
export type FilterKeys<Source, Condition> = {
[key in keyof Source]: Source[key] extends Condition ? key : never
}[keyof Source]
// Example usage:
interface User {
firstName: string
lastName: string
age: number
}
type UserStringKeys = FilterKeys<User, string> // 'firstName' | 'lastName'
Make RFCs easier to read#
Browser CSS
Ahh RFCs, the core documentation of the Internet, so useful at times, but still visually anchored in the 1980s. Let's make them look nicer with a bit of CSS, shall we ?
Copy and paste this in your console when viewing an RFC:
document
.querySelector('.content')
.setAttribute(
'style',
'margin:0 auto;font-size:16px;line-height:1.4;color:#333'
)