Skip to content

Latest commit

 

History

History
145 lines (110 loc) · 5.59 KB

jsdoc-tscheck.md

File metadata and controls

145 lines (110 loc) · 5.59 KB

Item 80: Use @ts-check and JSDoc to Experiment with TypeScript

Things to Remember

  • Add "// @ts-check" to the top of a JavaScript file to enable type checking without converting to TypeScript.
  • Recognize common errors. Know how to declare globals and add type declarations for third-party libraries.
  • Use JSDoc annotations for type assertions and better type inference.
  • Don't spend too much time getting your code perfectly typed with JSDoc. Remember that the goal is to convert to .ts!

Code Samples

// @ts-check
const person = {first: 'Grace', last: 'Hopper'};
2 * person.first
//  ~~~~~~~~~~~~ The right-hand side of an arithmetic operation must be of type
//               'any', 'number', 'bigint' or an enum type

💻 playground


// @ts-check
console.log(user.firstName);
//          ~~~~ Cannot find name 'user'

💻 playground


interface UserData {
  firstName: string;
  lastName: string;
}
declare let user: UserData;

💻 playground


// @ts-check
$('#graph').style({'width': '100px', 'height': '100px'});
// Error: Cannot find name '$'

💻 playground


// @ts-check
$('#graph').style({'width': '100px', 'height': '100px'});
//          ~~~~~ Property 'style' does not exist on type 'JQuery<HTMLElement>'

💻 playground


// @ts-check
const ageEl = document.getElementById('age');
ageEl.value = '12';
//    ~~~~~ Property 'value' does not exist on type 'HTMLElement'

💻 playground


// @ts-check
const ageEl = /** @type {HTMLInputElement} */(document.getElementById('age'));
ageEl.value = '12';  // OK

💻 playground


// @ts-check
/**
 * Gets the size (in pixels) of an element.
 * @param {Node} el The element
 * @return {{w: number, h: number}} The size
 */
function getSize(el) {
  const bounds = el.getBoundingClientRect();
  //                ~~~~~~~~~~~~~~~~~~~~~
  //     Property 'getBoundingClientRect' does not exist on type 'Node'
  return {width: bounds.width, height: bounds.height};
  //      ~~~~~ Type '{ width: any; height: any; }' is not
  //            assignable to type '{ w: number; h: number; }'
}

💻 playground


// @ts-check
/**
 * @param {number} val
 */
function double(val) {
  return 2 * val;
}

💻 playground


function loadData(data) {
  data.files.forEach(async file => {
    // ...
  });
}

💻 playground


/**
 * @param {{
 *  files: { forEach: (arg0: (file: any) => Promise<void>) => void; };
 * }} data
 */
function loadData(data) {
  // ...
}

💻 playground