Skip to content

tylerkilburn/howto-ts-check

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 

Repository files navigation

How to Use "ts-check"

Summary

This is short "How To" on using the awesome type safety of Typescript in Vanilla JS. It is an extremely flexible option for adding typing to JS and requires very little setup and no build process. You basically add a comment to the top of a file to enable checking and then annotate functions, variables, objects and classes as needed.

When ts-check is enabled, you also get implicit type checking for anything that VS Code can infer.

Adding to a File

At the top of your js file add the following comment

//@ts-check


Adding to your VS Code Settings

Add this to your settings.json in vs cod, shortcut via cmd + ,

{
  "js/ts.implicitProjectConfig.checkJs": true,
}

This will enable ts-check on all your js files by default. To explicitly opt out of type checking add this to a file:

//@ts-nocheck


Annotating

Variables

Annotate next line:

/** @type {string} */
var myVarAsString = dataFromSomethingFnCall();

Annotate inline - note use of parens to wrap expression:

var myVarAsNumber = /** @type {number} */(dataFromSomethingFnCall());

Variable (Inline) Template

/** @type {__TYPE__} */
/** @type {__TYPE__} */ ()


Functions

/**
 * @param {string} a
 * @return {string}
 */
const myFun = (a, b) => {
  // code
  return something();
}

Typing this

/**
 * @this {MyType}
 * @param {string} a
 * @param {number} b
 * @return {number}
 */
function(a, b) {
  //...code
}

Function Template

/**
 * @param {__TYPE__} __NAME__
 * @return {__TYPE__}
 */


Interfaces / Custom Types

To Create a Custom Type

/**
 * @typedef { "NORTH" | "EAST" | "SOUTH" | "WEST" } CompassDirection
 */

To Create an Interface

/**
 * @typedef {Object} IAwesomeType
 * @property {string} keyA
 * @property {number} keyB
 * @property {CompassDirection} keyC
 * @property {IMyOtherInterface} keyD
 */

Interface Template

/**
 * @typedef {Object} __NAME__
 * @property {__TYPE__} __NAME__
 */


Classes

class CoordinatePoint {
    /**
     * @param {number} x
     * @param {number} y
     */
    constructor(x, y) {
        // ...
    }

    /**
     * @return {number}
     */
    getX() {
        // ...
    }

    /**
     * @return {number}
     */
    getY() {
        // ...
    }

    /**
     * @param {string} str
     * @return {CoordinatePoint}
     */
    static fromString(str) {
        // ...
    }
}


"Import" Types

You can import from typescript or TS type definition files with the following annotation IAwesomeType would be available for use in the current file after doing this.

/**
 * @typedef {import("./to/my/path/file.d.ts").IAwesomeType} IAwesomeType
 */

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published