TypeScript 2.3 and later support type-checking and reporting errors in .js files with —checkJs.

You can skip checking some files by adding a // @ts-nocheck comment to them; conversely, you can choose to check only a few .js files by adding a // @ts-check comment to them without setting —checkJs.You can also ignore errors on specific lines by adding // @ts-ignore on the preceding line.Note that if you have a tsconfig.json, JS checking will respect strict flags like noImplicitAny, strictNullChecks, etc.However, because of the relative looseness of JS checking, combining strict flags with it may be surprising.

Here are some notable differences on how checking works in .js files compared to .ts files:

JSDoc types are used for type information

In a .js file, types can often be inferred just like in .ts files.Likewise, when types can’t be inferred, they can be specified using JSDoc the same way that type annotations are used in a .ts file.Just like Typescript, —noImplicitAny will give you errors on the places that the compiler could not infer a type.(With the exception of open-ended object literals; see below for details.)

JSDoc annotations adorning a declaration will be used to set the type of that declaration. For example:

  1. /** @type {number} */
  2. var x;
  3. x = 0; // OK
  4. x = false; // Error: boolean is not assignable to number

You can find the full list of supported JSDoc patterns below.

Properties are inferred from assignments in class bodies

ES2015 does not have a means for declaring properties on classes. Properties are dynamically assigned, just like object literals.

In a .js file, the compiler infers properties from property assignments inside the class body.The type of a property is the type given in the constructor, unless it’s not defined there, or the type in the constructor is undefined or null.In that case, the type is the union of the types of all the right-hand values in these assignments.Properties defined in the constructor are always assumed to exist, whereas ones defined just in methods, getters, or setters are considered optional.

  1. class C {
  2. constructor() {
  3. this.constructorOnly = 0
  4. this.constructorUnknown = undefined
  5. }
  6. method() {
  7. this.constructorOnly = false // error, constructorOnly is a number
  8. this.constructorUnknown = "plunkbat" // ok, constructorUnknown is string | undefined
  9. this.methodOnly = 'ok' // ok, but methodOnly could also be undefined
  10. }
  11. method2() {
  12. this.methodOnly = true // also, ok, methodOnly's type is string | boolean | undefined
  13. }
  14. }

If properties are never set in the class body, they are considered unknown.If your class has properties that are only read from, add and then annotate a declaration in the constructor with JSDoc to specify the type.You don’t even have to give a value if it will be initialised later:

  1. class C {
  2. constructor() {
  3. /** @type {number | undefined} */
  4. this.prop = undefined;
  5. /** @type {number | undefined} */
  6. this.count;
  7. }
  8. }
  9. let c = new C();
  10. c.prop = 0; // OK
  11. c.count = "string"; // Error: string is not assignable to number|undefined

Constructor functions are equivalent to classes

Before ES2015, Javascript used constructor functions instead of classes.The compiler supports this pattern and understands constructor functions as equivalent to ES2015 classes.The property inference rules described above work exactly the same way.

  1. function C() {
  2. this.constructorOnly = 0
  3. this.constructorUnknown = undefined
  4. }
  5. C.prototype.method = function() {
  6. this.constructorOnly = false // error
  7. this.constructorUnknown = "plunkbat" // OK, the type is string | undefined
  8. }

CommonJS modules are supported

In a .js file, Typescript understands the CommonJS module format.Assignments to exports and module.exports are recognized as export declarations.Similarly, require function calls are recognized as module imports. For example:

  1. // same as `import module "fs"`
  2. const fs = require("fs");
  3. // same as `export function readFile`
  4. module.exports.readFile = function(f) {
  5. return fs.readFileSync(f);
  6. }

The module support in Javascript is much more syntactically forgiving than Typescript’s module support.Most combinations of assignments and declarations are supported.

Classes, functions, and object literals are namespaces

Classes are namespaces in .js files.This can be used to nest classes, for example:

  1. class C {
  2. }
  3. C.D = class {
  4. }

And, for pre-ES2015 code, it can be used to simulate static methods:

  1. function Outer() {
  2. this.y = 2
  3. }
  4. Outer.Inner = function() {
  5. this.yy = 2
  6. }

It can also be used to create simple namespaces:

  1. var ns = {}
  2. ns.C = class {
  3. }
  4. ns.func = function() {
  5. }

Other variants are allowed as well:

  1. // IIFE
  2. var ns = (function (n) {
  3. return n || {};
  4. })();
  5. ns.CONST = 1
  6. // defaulting to global
  7. var assign = assign || function() {
  8. // code goes here
  9. }
  10. assign.extra = 1

Object literals are open-ended

In a .ts file, an object literal that initializes a variable declaration gives its type to the declaration.No new members can be added that were not specified in the original literal.This rule is relaxed in a .js file; object literals have an open-ended type (an index signature) that allows adding and looking up properties that were not defined originally.For instance:

  1. var obj = { a: 1 };
  2. obj.b = 2; // Allowed

Object literals behave as if they have an index signature [x:string]: any that allows them to be treated as open maps instead of closed objects.

Like other special JS checking behaviors, this behavior can be changed by specifying a JSDoc type for the variable. For example:

  1. /** @type {{a: number}} */
  2. var obj = { a: 1 };
  3. obj.b = 2; // Error, type {a: number} does not have property b

null, undefined, and empty array initializers are of type any or any[]

Any variable, parameter or property that is initialized with null or undefined will have type any, even if strict null checks is turned on.Any variable, parameter or property that is initialized with [] will have type any[], even if strict null checks is turned on.The only exception is for properties that have multiple initializers as described above.

  1. function Foo(i = null) {
  2. if (!i) i = 1;
  3. var j = undefined;
  4. j = 2;
  5. this.l = [];
  6. }
  7. var foo = new Foo();
  8. foo.l.push(foo.i);
  9. foo.l.push("end");

Function parameters are optional by default

Since there is no way to specify optionality on parameters in pre-ES2015 Javascript, all function parameters in .js file are considered optional.Calls with fewer arguments than the declared number of parameters are allowed.

It is important to note that it is an error to call a function with too many arguments.

For instance:

  1. function bar(a, b) {
  2. console.log(a + " " + b);
  3. }
  4. bar(1); // OK, second argument considered optional
  5. bar(1, 2);
  6. bar(1, 2, 3); // Error, too many arguments

JSDoc annotated functions are excluded from this rule.Use JSDoc optional parameter syntax to express optionality. e.g.:

  1. /**
  2. * @param {string} [somebody] - Somebody's name.
  3. */
  4. function sayHello(somebody) {
  5. if (!somebody) {
  6. somebody = 'John Doe';
  7. }
  8. console.log('Hello ' + somebody);
  9. }
  10. sayHello();

Var-args parameter declaration inferred from use of arguments

A function whose body has a reference to the arguments reference is implicitly considered to have a var-arg parameter (i.e. (…arg: any[]) => any). Use JSDoc var-arg syntax to specify the type of the arguments.

  1. /** @param {...number} args */
  2. function sum(/* numbers */) {
  3. var total = 0
  4. for (var i = 0; i < arguments.length; i++) {
  5. total += arguments[i]
  6. }
  7. return total
  8. }

Unspecified type parameters default to any

Since there is no natural syntax for specifying generic type parameters in Javascript, an unspecified type parameter defaults to any.

In extends clause

For instance, React.Component is defined to have two type parameters, Props and State.In a .js file, there is no legal way to specify these in the extends clause. By default the type arguments will be any:

  1. import { Component } from "react";
  2. class MyComponent extends Component {
  3. render() {
  4. this.props.b; // Allowed, since this.props is of type any
  5. }
  6. }

Use JSDoc @augments to specify the types explicitly. for instance:

  1. import { Component } from "react";
  2. /**
  3. * @augments {Component<{a: number}, State>}
  4. */
  5. class MyComponent extends Component {
  6. render() {
  7. this.props.b; // Error: b does not exist on {a:number}
  8. }
  9. }

In JSDoc references

An unspecified type argument in JSDoc defaults to any:

  1. /** @type{Array} */
  2. var x = [];
  3. x.push(1); // OK
  4. x.push("string"); // OK, x is of type Array<any>
  5. /** @type{Array.<number>} */
  6. var y = [];
  7. y.push(1); // OK
  8. y.push("string"); // Error, string is not assignable to number

In function calls

A call to a generic function uses the arguments to infer the type parameters. Sometimes this process fails to infer any types, mainly because of lack of inference sources; in these cases, the type parameters will default to any. For example:

  1. var p = new Promise((resolve, reject) => { reject() });
  2. p; // Promise<any>;

Supported JSDoc

The list below outlines which constructs are currently supported when using JSDoc annotations to provide type information in JavaScript files.

Note any tags which are not explicitly listed below (such as @async) are not yet supported.

  • @type
  • @param (or @arg or @argument)
  • @returns (or @return)
  • @typedef
  • @callback
  • @template
  • @class (or @constructor)
  • @this
  • @extends (or @augments)
  • @enum

The meaning is usually the same, or a superset, of the meaning of the tag given at usejsdoc.org.The code below describes the differences and gives some example usage of each tag.

@type

You can use the “@type” tag and reference a type name (either primitive, defined in a TypeScript declaration, or in a JSDoc “@typedef” tag).You can use any Typescript type, and most JSDoc types.

  1. /**
  2. * @type {string}
  3. */
  4. var s;
  5. /** @type {Window} */
  6. var win;
  7. /** @type {PromiseLike<string>} */
  8. var promisedString;
  9. // You can specify an HTML Element with DOM properties
  10. /** @type {HTMLElement} */
  11. var myElement = document.querySelector(selector);
  12. element.dataset.myData = '';

@type can specify a union type — for example, something can be either a string or a boolean.

  1. /**
  2. * @type {(string | boolean)}
  3. */
  4. var sb;

Note that parentheses are optional for union types.

  1. /**
  2. * @type {string | boolean}
  3. */
  4. var sb;

You can specify array types using a variety of syntaxes:

  1. /** @type {number[]} */
  2. var ns;
  3. /** @type {Array.<number>} */
  4. var nds;
  5. /** @type {Array<number>} */
  6. var nas;

You can also specify object literal types.For example, an object with properties ‘a’ (string) and ‘b’ (number) uses the following syntax:

  1. /** @type {{ a: string, b: number }} */
  2. var var9;

You can specify map-like and array-like objects using string and number index signatures, using either standard JSDoc syntax or Typescript syntax.

  1. /**
  2. * A map-like object that maps arbitrary `string` properties to `number`s.
  3. *
  4. * @type {Object.<string, number>}
  5. */
  6. var stringToNumber;
  7. /** @type {Object.<number, object>} */
  8. var arrayLike;

The preceding two types are equivalent to the Typescript types { [x: string]: number } and { [x: number]: any }. The compiler understands both syntaxes.

You can specify function types using either Typescript or Closure syntax:

  1. /** @type {function(string, boolean): number} Closure syntax */
  2. var sbn;
  3. /** @type {(s: string, b: boolean) => number} Typescript syntax */
  4. var sbn2;

Or you can just use the unspecified Function type:

  1. /** @type {Function} */
  2. var fn7;
  3. /** @type {function} */
  4. var fn6;

Other types from Closure also work:

  1. /**
  2. * @type {*} - can be 'any' type
  3. */
  4. var star;
  5. /**
  6. * @type {?} - unknown type (same as 'any')
  7. */
  8. var question;

Casts

Typescript borrows cast syntax from Closure.This lets you cast types to other types by adding a @type tag before any parenthesized expression.

  1. /**
  2. * @type {number | string}
  3. */
  4. var numberOrString = Math.random() < 0.5 ? "hello" : 100;
  5. var typeAssertedNumber = /** @type {number} */ (numberOrString)

Import types

You can also import declarations from other files using import types.This syntax is Typescript-specific and differs from the JSDoc standard:

  1. /**
  2. * @param p { import("./a").Pet }
  3. */
  4. function walk(p) {
  5. console.log(`Walking ${p.name}...`);
  6. }

import types can also be used in type alias declarations:

  1. /**
  2. * @typedef { import("./a").Pet } Pet
  3. */
  4. /**
  5. * @type {Pet}
  6. */
  7. var myPet;
  8. myPet.name;

import types can be used to get the type of a value from a module if you don’t know the type, or if it has a large type that is annoying to type:

  1. /**
  2. * @type {typeof import("./a").x }
  3. */
  4. var x = require("./a").x;

@param and @returns

@param uses the same type syntax as @type, but adds a parameter name.The parameter may also be declared optional by surrounding the name with square brackets:

  1. // Parameters may be declared in a variety of syntactic forms
  2. /**
  3. * @param {string} p1 - A string param.
  4. * @param {string=} p2 - An optional param (Closure syntax)
  5. * @param {string} [p3] - Another optional param (JSDoc syntax).
  6. * @param {string} [p4="test"] - An optional param with a default value
  7. * @return {string} This is the result
  8. */
  9. function stringsStringStrings(p1, p2, p3, p4){
  10. // TODO
  11. }

Likewise, for the return type of a function:

  1. /**
  2. * @return {PromiseLike<string>}
  3. */
  4. function ps(){}
  5. /**
  6. * @returns {{ a: string, b: number }} - May use '@returns' as well as '@return'
  7. */
  8. function ab(){}

@typedef, @callback, and @param

@typedef may be used to define complex types.Similar syntax works with @param.

  1. /**
  2. * @typedef {Object} SpecialType - creates a new type named 'SpecialType'
  3. * @property {string} prop1 - a string property of SpecialType
  4. * @property {number} prop2 - a number property of SpecialType
  5. * @property {number=} prop3 - an optional number property of SpecialType
  6. * @prop {number} [prop4] - an optional number property of SpecialType
  7. * @prop {number} [prop5=42] - an optional number property of SpecialType with default
  8. */
  9. /** @type {SpecialType} */
  10. var specialTypeObject;

You can use either object or Object on the first line.

  1. /**
  2. * @typedef {object} SpecialType1 - creates a new type named 'SpecialType1'
  3. * @property {string} prop1 - a string property of SpecialType1
  4. * @property {number} prop2 - a number property of SpecialType1
  5. * @property {number=} prop3 - an optional number property of SpecialType1
  6. */
  7. /** @type {SpecialType1} */
  8. var specialTypeObject1;

@param allows a similar syntax for one-off type specifications.Note that the nested property names must be prefixed with the name of the parameter:

  1. /**
  2. * @param {Object} options - The shape is the same as SpecialType above
  3. * @param {string} options.prop1
  4. * @param {number} options.prop2
  5. * @param {number=} options.prop3
  6. * @param {number} [options.prop4]
  7. * @param {number} [options.prop5=42]
  8. */
  9. function special(options) {
  10. return (options.prop4 || 1001) + options.prop5;
  11. }

@callback is similar to @typedef, but it specifies a function type instead of an object type:

  1. /**
  2. * @callback Predicate
  3. * @param {string} data
  4. * @param {number} [index]
  5. * @returns {boolean}
  6. */
  7. /** @type {Predicate} */
  8. const ok = s => !(s.length % 2);

Of course, any of these types can be declared using Typescript syntax in a single-line @typedef:

  1. /** @typedef {{ prop1: string, prop2: string, prop3?: number }} SpecialType */
  2. /** @typedef {(data: string, index?: number) => boolean} Predicate */

@template

You can declare generic types with the @template tag:

  1. /**
  2. * @template T
  3. * @param {T} x - A generic parameter that flows through to the return type
  4. * @return {T}
  5. */
  6. function id(x){ return x }

Use comma or multiple tags to declare multiple type parameters:

  1. /**
  2. * @template T,U,V
  3. * @template W,X
  4. */

You can also specify a type constraint before the type parameter name.Only the first type parameter in a list is constrained:

  1. /**
  2. * @template {string} K - K must be a string or string literal
  3. * @template {{ serious(): string }} Seriousalizable - must have a serious method
  4. * @param {K} key
  5. * @param {Seriousalizable} object
  6. */
  7. function seriousalize(key, object) {
  8. // ????
  9. }

@constructor

The compiler infers constructor functions based on this-property assignments, but you can make checking stricter and suggestions better if you add a @constructor tag:

  1. /**
  2. * @constructor
  3. * @param {number} data
  4. */
  5. function C(data) {
  6. this.size = 0;
  7. this.initialize(data); // Should error, initializer expects a string
  8. }
  9. /**
  10. * @param {string} s
  11. */
  12. C.prototype.initialize = function (s) {
  13. this.size = s.length
  14. }
  15. var c = new C(0);
  16. var result = C(1); // C should only be called with new

With @constructor, this is checked inside the constructor function C, so you will get suggestions for the initialize method and an error if you pass it a number. You will also get an error if you call C instead of constructing it.

Unfortunately, this means that constructor functions that are also callable cannot use @constructor.

@this

The compiler can usually figure out the type of this when it has some context to work with. When it doesn’t, you can explicitly specify the type of this with @this:

  1. /**
  2. * @this {HTMLElement}
  3. * @param {*} e
  4. */
  5. function callbackForLater(e) {
  6. this.clientHeight = parseInt(e) // should be fine!
  7. }

@extends

When Javascript classes extend a generic base class, there is nowhere to specify what the type parameter should be. The @extends tag provides a place for that type parameter:

  1. /**
  2. * @template T
  3. * @extends {Set<T>}
  4. */
  5. class SortableSet extends Set {
  6. // ...
  7. }

Note that @extends only works with classes. Currently, there is no way for a constructor function extend a class.

@enum

The @enum tag allows you to create an object literal whose members are all of a specified type. Unlike most object literals in Javascript, it does not allow other members.

  1. /** @enum {number} */
  2. const JSDocState = {
  3. BeginningOfLine: 0,
  4. SawAsterisk: 1,
  5. SavingComments: 2,
  6. }

Note that @enum is quite different from, and much simpler than, Typescript’s enum. However, unlike Typescript’s enums, @enum can have any type:

  1. /** @enum {function(number): number} */
  2. const Math = {
  3. add1: n => n + 1,
  4. id: n => -n,
  5. sub1: n => n - 1,
  6. }

More examples

  1. var someObj = {
  2. /**
  3. * @param {string} param1 - Docs on property assignments work
  4. */
  5. x: function(param1){}
  6. };
  7. /**
  8. * As do docs on variable assignments
  9. * @return {Window}
  10. */
  11. let someFunc = function(){};
  12. /**
  13. * And class methods
  14. * @param {string} greeting The greeting to use
  15. */
  16. Foo.prototype.sayHi = (greeting) => console.log("Hi!");
  17. /**
  18. * And arrow functions expressions
  19. * @param {number} x - A multiplier
  20. */
  21. let myArrow = x => x * x;
  22. /**
  23. * Which means it works for stateless function components in JSX too
  24. * @param {{a: string, b: number}} test - Some param
  25. */
  26. var fc = (test) => <div>{test.a.charAt(0)}</div>;
  27. /**
  28. * A parameter can be a class constructor, using Closure syntax.
  29. *
  30. * @param {{new(...args: any[]): object}} C - The class to register
  31. */
  32. function registerClass(C) {}
  33. /**
  34. * @param {...string} p1 - A 'rest' arg (array) of strings. (treated as 'any')
  35. */
  36. function fn10(p1){}
  37. /**
  38. * @param {...string} p1 - A 'rest' arg (array) of strings. (treated as 'any')
  39. */
  40. function fn9(p1) {
  41. return p1.join();
  42. }

Patterns that are known NOT to be supported

Referring to objects in the value space as types doesn’t work unless the object also creates a type, like a constructor function.

  1. function aNormalFunction() {
  2. }
  3. /**
  4. * @type {aNormalFunction}
  5. */
  6. var wrong;
  7. /**
  8. * Use 'typeof' instead:
  9. * @type {typeof aNormalFunction}
  10. */
  11. var right;

Postfix equals on a property type in an object literal type doesn’t specify an optional property:

  1. /**
  2. * @type {{ a: string, b: number= }}
  3. */
  4. var wrong;
  5. /**
  6. * Use postfix question on the property name instead:
  7. * @type {{ a: string, b?: number }}
  8. */
  9. var right;

Nullable types only have meaning if strictNullChecks is on:

  1. /**
  2. * @type {?number}
  3. * With strictNullChecks: true -- number | null
  4. * With strictNullChecks: off -- number
  5. */
  6. var nullable;

Non-nullable types have no meaning and are treated just as their original type:

  1. /**
  2. * @type {!number}
  3. * Just has type number
  4. */
  5. var normal;

Unlike JSDoc’s type system, Typescript only allows you to mark types as containing null or not.There is no explicit non-nullability – if strictNullChecks is on, then number is not nullable.If it is off, then number is nullable.