Skip to content

Instantly share code, notes, and snippets.

@haileys
Last active November 21, 2017 06:41
Show Gist options
  • Save haileys/eb98a90433654530e67aad2f101d8752 to your computer and use it in GitHub Desktop.
Save haileys/eb98a90433654530e67aad2f101d8752 to your computer and use it in GitHub Desktop.
function query<T>(selector: string, klass: Class<T>): T {
let element = document.querySelector(selector);
if (!(element instanceof klass)) {
throw new TypeError("expected " + selector + " to select element of type " + (klass : Function).name);
}
return element;
}
// legit:
let audio = query("audio", HTMLAudioElement);
// type error:
let audio: HTMLSpanElement = query("audio", HTMLAudioElement);
// 33: let audio: HTMLSpanElement = query("audio", HTMLAudioElement);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ HTMLAudioElement. This type is incompatible with
// 33: let audio: HTMLSpanElement = query("audio", HTMLAudioElement);
// ^^^^^^^^^^^^^^^ HTMLSpanElement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment