在打字稿中,我可以执行以下操作:
const foo = <T>({ someArg }: { someArg: T }) => someArg
foo({ someArg: 4 }) // returns a number
foo({ someArg: "cool" }) // returns a string
我该如何使用jsdoc / checkjs进行等效处理?我以为它会像这样:
/**
* @template T
*
* @param {object} props
* @param {T} props.someArg
* @returns {T}
*/
const foo = ({ someArg }) => someArg
foo({ someArg: 4 })
foo({ someArg: 'cool' })
但是我收到一个看起来像这样的错误:
src/components/example.js:10:7 - error TS2322: Type 'number' is not assignable to type 'T'.
10 foo({ someArg: 4 })
~~~~~~~
src/components/example.js:5:4
5 * @param {T} props.someArg
~~~~~~~~~~~~~~~~~~~~~~~~
6 * @returns {T}
~~~
The expected type comes from property 'someArg' which is declared here on type '{ someArg: T; }'
src/components/example.js:11:7 - error TS2322: Type 'string' is not assignable to type 'T'.
11 foo({ someArg: 'cool' })
~~~~~~~
src/components/example.js:5:4
5 * @param {T} props.someArg
~~~~~~~~~~~~~~~~~~~~~~~~
6 * @returns {T}
~~~
The expected type comes from property 'someArg' which is declared here on type '{ someArg: T; }'
~~~~~~~
不破坏args似乎可以:
/**
* @template T
*
* @param {object} props
* @param {T} props.someArg
* @returns {T}
*/
const foo = props => props.someArg
更新-我认为可能是这个问题: Generic types from JSDoc aren't really generic