Taking advantage of TypeScript in JavaScript development

Original author: Ryan Paul
  • Transfer

Microsoft's TypeScript programming language brings many of the benefits of static typing to JavaScript. Despite the fact that it does not check types at runtime, it allows for more accurate static analysis, increases security and opens up opportunities for better integration with the IDE. TypeScript code usually translates into standard JavaScript, which runs in browsers or Node.js. Given the appeal of TypeScript, it is not surprising that its popularity is growing rapidly .


Of course, the use of a non-standard dialect of the language is not without objective flaws. Using TypeScript in your project will require an additional step when building the project, it excludes the possibility of using a wide range of tools that are designed only for JavaScript. Also, all team members will have to study non-standard functions for JS. Also, taking into account the speed of JavaScript development, there is some risk of getting dependent on non-standard functionality. TypeScript developers designed the language based on some potential problems, but nevertheless, this is not "vanilla" JavaScript.


Fortunately, JavaScript developers can get some of the benefits using a familiar tool. TypeScript 2.3, which was released in April 2017, added support for the analysis of regular JavaScript code indicating the types in the comments. You can use JSDoc-like syntax to describe function signatures and add type information. TypeScript tools read annotations in comments and use them in much the same way as in their own type system.


JavaScript code with annotations in comments is more verbose than TypeScript, but it works everywhere, does not require transpiling, and allows selective use of typing where necessary. So far, it does not cover all the features of TypeScript, but is already functional enough to be useful.


Working example


In order to enable the analysis of JavaScript code using TypeScript, simply add a comment with text @ts-checkat the beginning of the file. Then you can add annotations indicating the types within this file. The following example shows a description of a function signature with two parameters and a specific return type.


// @ts-check
/**
 * @param {number} a
 * @param {number} b
 * @return {number}
 */
function example(a, b) {
    return a + b;
}

Visual Studio Code, which supports TypeScript out of the box, automatically finds such comments and enables validation mode. This will require absolutely no configuration. You don’t even have to create a configuration file for TypeScript. Just add comments in any JavaScript code. If after this you try to call the function with the wrong arguments, the editor will display a warning.



The editor will also use annotations to improve other features, such as auto-completion. In addition, type information is successfully used between files due to the fact that TypeScript understands ES6 imports requirein Node.js.


You can also use annotations to indicate the structure of a regular object. This can be useful when you want to get auto-completion of object properties and checking their availability for JSON data received from any API. The following example shows how you can describe the structure of an object using annotations.


/**
 * @typedef {Object} Issue
 * @property {string} url
 * @property {string} repository_url
 * @property {id} number
 * @property {string} title
 * @property {string} state
 * @property {bool} open
 */
const url = "https://api.github.com/repos/microsoft/typescript/issues";
(async () => {
  let response = await got(url, {json: true});
  /** @type {Issue[]} */
  let issues = response.body;
  for (let issue of issues)
    console.log(issue.title);
})();

This example uses a special annotation @typedefto determine the type of object Issue. Further in the data acquisition function, we indicate with the help @typethat the received response is an array of objects Issue.


You can find more examples of using annotations in the TypeScript wiki.


Library support


TypeScript already has type indications for the standard Node.js library, so you can use the checks and the addition of almost all of its functions out of the box. Some third-party libraries also have a type file (usually a file with an extension d.ts) in their npm packages. Adding @ts-checkfor your project will also take into account the types of functions and objects imported from such libraries.



Conclusion


All last year I tried to simplify my JavaScript development tools and get away from the increasing complexity and redundancy that affects modern web development. Using annotations in comments is a good way to stick to this strategy. I get the benefits of TypeScript without adding an extra step when building the project during development. This is similar to using TypeScript as a smart linter, not a programming language. I don’t even need to add it depending on my project. I just turn on type checking as a simple editor function and this allows me to write code better.


Also popular now: