Skip to content

Instantly share code, notes, and snippets.

@rbiggs
Created September 3, 2018 04:35
Show Gist options
  • Save rbiggs/45d3b59a72c1965c551ece398c67ce1e to your computer and use it in GitHub Desktop.
Save rbiggs/45d3b59a72c1965c551ece398c67ce1e to your computer and use it in GitHub Desktop.
Example of JSDoc type casting.
// Create a button element.
// Type will be Node.
const btn = document.createElement('button')
// Because type is Node, we cannot call setAttribute,
// since this is on the Element type.
// Performing a type cast from Node to Element fixes this:
/** @type {Element} */(btn).setAttribute('disabled', true)
@ExE-Boss
Copy link

This is unnecessary in this case as the return type of document.createElement is Element, and if you pass a statically known string (eg.: 'button', then the return value becomes HTMLButtonElement):
https://github.com/Microsoft/TypeScript/blob/a41a27694ac9ca2848fb83cc0a5414c4c2c5338e/lib/lib.dom.d.ts#L17187-L17303

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment