Correct JSDoc signature for is_string function?

Viewed 20

I have the following function of type (obj:any)=>boolean that determines whether an object is string or not. I want the JsDoc to be "smart" so that whenever I use if(isString(x)){ ...block... }, the highlighter treats x inside the block as a string.

So far I tried this without success:

/** @type {((obj:string)=>true)|((obj:any)=>false)} */
function isString(obj) {
  return Object.prototype.toString.call(obj) === "[object String]";
}

How can I do it properly?

1 Answers

The following should do the trick. It uses the Typescript's narrowing with type predicates.

/** @type {(obj: any) => obj is String} */
function isString(obj) {
  return Object.prototype.toString.call(obj) === "[object String]";
}
Related