BeyondCodeBootcamp / BeyondCodeBootcamp/js-with-types-jsdoc-tsc-starter
Bug in `tsc`: can't export package-scope types
- Dominant language
- JavaScript
- Stars
- 19
- Forks
- 1
- PR merge metrics
- No merged PRs in 30d
Description
You can either have types scoped to the level of the package, or you can export them, but you can't do both:
See
- https://github.com/coolaj86/test-case-tsc-exports
- https://stackoverflow.com/questions/73480632/how-can-i-export-package-scope-jsdoc-types
- https://github.com/microsoft/TypeScript/issues/50436
## ⚠️ Workaround
You can import your own exported types.
### in package "foo"
```js
// types.js
/**
* @typedef {Object} Foo
* @prop {String} name
*/
```
```js
// index.js
/** @typedef {import('./types.js').Foo} Foo */
/** @type {Foo} */
let foo;
```
### in package "bar"
```js
/** @type {import('foo/types.js').Foo} */
let foo;
```
# Perfect Solution: Re-export with types
Make `index.js` be a re-export with all of the local types, then generate the local types.js:
`package.json`:
```json5
{
"main": "index.js", // our types + package re-export
"files": [
"foo.js",
"types.js"
]
}
```
```sh
npm pkg set scripts.prepublish="./bin/re-export-types"
```
`index.js`:
```js
module.exports = require('./');
/**
* @typedef {Object} Bar
* @prop {Number} age
*/
/**
* @typedef {Object} Foo
* @prop {String} name
*/
```
### Generate `types.js`
`./bin/re-export-types`:
```sh
#!/bin/sh
my_typedefs="$(
grep typedef ./index.js | cut -d ' ' -f5
)"
rm -f ./types.js
{
echo '// auto-generated with ./bin/re-export-types'
echo '// DO NOT EDIT'
echo ''
echo '/**'
for my_type in $my_typedefs; do
echo " * @typedef {import('./').${my_type}} ${my_type}"
done
echo ' */'
} >> ./types.js
```
```js
/**
* @typedef {import('./').Foo} Foo
* @typedef {import('./').Bar} Bar
*/
```
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with the linked reproduction, Stack Overflow discussion, and TypeScript issue 50436 to understand the package-scope export behavior. Then inspect the package.json, index.js, and bin/re-export-types examples in this issue; done means the package-scope types are both available locally and exportable without relying on the documented workaround.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, typescript
- Domain
- compilers, tooling
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100