I've been trying to write a TypeScript wrapper around document.getElementById. I've got something that I'm almost happy with, so I'll start with that, then I'll explain my motivations and you can decide whether this makes sense or not, or which of my assumptions is most wrong.
There's a type guard, which means it will throw an exception if document.getElementById returns an element of the wrong type.
There's also what I'm calling a variable name guard. The wrapper returns an object with a single property with the same name as the html id. This stops the variable name from getting out of sync with the id accidentally - a mistake I seem to be quite prone to, I'm afraid.
Here's the code:
export const getElementById = <K extends string, V extends HTMLElement>(
elementType: { new (): V },
id: K,
): Record<K, V> => {
const elm = document.getElementById(id);
if (elm instanceof elementType) {
return { [id]: elm } as Record<K, V>;
} else if (elm === null) {
throw new Error(`Element ${id} not found`);
} else {
throw new Error(`Element ${id} is of unexpected type, ${elm.nodeName}`);
}
};
And it's called like this:
import { getElementById } from './getElementById';
const { mmEditor } = getElementById(HTMLTextAreaElement, 'mmEditor');
const { parseButton } = getElementById(HTMLElement, 'parseButton');
const { parseOutput } = getElementById(HTMLElement, 'parseOutput');
const { mmpEditor } = getElementById(HTMLTextAreaElement, 'mmpEditor');
const { unifyButton } = getElementById(HTMLElement, 'unifyButton');
const { unifierOutput } = getElementById(HTMLElement, 'unifierOutput');
When presented with vanilla html DOM code like this, the first question I would always ask is: why haven't I used a web-framework?
In this case, there's a package that I've written, and I wish to demonstrate its use in a web environment. So I'm trying to be inclusive, and write something you can hopefully follow whether your preferred framework is React, Angular, Vue, etc. It being demo code also explains why I wanted nice clearly worded exceptions and then made no effort to catch them.
I have unconsciously excluded JavaScript developers, however. Previously I have written such examples in JavaScript in the hope to include everyone. But this time I automatically chose TypeScript and didn't realize what I'd done until I'd almost finished it. It's 2026, is it OK to exclude JavaScript devs?
The only thing that makes me unhappy about this code is the 'as' statement. You should be able to satisfy yourself that it's correct and the type can't be anything else, but - and this is kind of the point of using a typed language - I'd rather you didn't have to. Unfortunately it's an inference that TypeScript itself doesn't appear to be able to make, and I can't find a way around that.
The elementType which is passed in might be worth elaborating on. I started with one function per element type, and when I combined them, I ended up with this, which would be nice if it would compile
const getElementId = <T extends HTMLElement>(id: keyof Record<string, T>) => {
const elm = document.getElementById(String(id));
if (elm instanceof T) {
return { [id]: elm } as Record<string, T>;
} else {
throw new Error(`Element ${id} not found or wrong type`);
}
}
src/index.ts:23:24 - error TS2693: 'T' only refers to a type, but is being used as a value here.
But it's hobbled by the need to transpile into JavaScript and can't take the type with it. So we pass the elementType in instead, which is defined as an object which has a constructor returning the expected element type. That we can do an instanceof on.
Thanks for reading. It's been nice to have a small piece of code with an easily understood purpose to talk about. That doesn't happen very often. When I start writing a program I'm happy to put any old runtime type check in, just to pander to the compiler's whims, but here I've finished up with something that does make it easy to hack around with a piece of code because it tells me clearly when I inevitably screw up. Anything with a generic in it is always a fun puzzle, I find, and I mean that both in a good and a bad way. I hope you found this interesting, what do you think?