Skip to content

In JS, cannot declare a function as a type guard #26297

@AlCalzone

Description

@AlCalzone

TypeScript Version: 3.1.0-dev.20180808

Search Terms: jsdoc type guard

Declaring a function as a type guard does not seem to work in JS.
any can be replaced with unknown but that doesn't change anything. The following example is trivial yet shows the issue:

Code

// filename: index.js

// @ts-check

/**
 * @param {any} value
 * @return {value is boolean}
 */
function isBoolean(value) {
	return typeof value === "boolean";
}

// Errors here:
// @return {value is boolean}
//                ~~ "}" expected (sometimes)
//          ~~~~~ the name "value" was not found

/** @param {any} val */
function foo(val) {
	if (isBoolean(val)) {
		val; // still has type `any`
	}
}

Expected behavior:

  • No error at the @returns tag
  • inside the if-branch, val is of type boolean

Related Issues: #25127

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptDomain: JSDocRelates to JSDoc parsing and type generationFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions