Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

typescript - How to pass a generic type argument with JSDoc?

Before giving up I wanted to give it a shot here.

I have a definition file with typings like the following:

/**
 * My json decode function, in reality very different
 * implementation (class like) but it works as an example
 */
  function decodeJSON<T = unknown>(str: string): T;

If I wanted to use this generic in TypeScript I would do something like the following

const value = decodeJSON<number[]>("[1,2,3]"); // return type will be number[]

However in my actual code I can't use TypeScript, only it's typings for development purposes, and I can't seem to find a way to tell my editor what the type I'm passing to the generic parameter is so that I get the correct type information.

I've tried to use JSDoc to specify what the parameter for the generic might be the same way that TypeScript can

// I was expecting JSDoc to understand something like this, but it doesn't
/** @type {decodeJSON<number[]>} */
const value = decodeJSON("[1,2,3]"); // Type inference will be unknown

But it doesn't work. I don't really care what the result might be in runtime, I have sanity checks for that already implemented. I just want my editor to give me type hints about the generic function result to make my job (this function has some heavy use in my app) easier

My editor is WebStorm in case it matters, but this seems to be a general limitation of JSDoc


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Apparently this isn't something that JSDoc can do, even though the need for it is kinda real

https://github.com/microsoft/TypeScript/issues/27387


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...