Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...