Skip to content
This repository has been archived by the owner on Aug 11, 2021. It is now read-only.

Commit

Permalink
fix: types again
Browse files Browse the repository at this point in the history
If we require a JS class `Foo`, then export it as a property of an object,
ts thinks we are exporting `typeof Foo` rather than the `Foo` constructor.

At runtime `typeof` gets erased so ts gets upset by things like:

```js
const { DAGNode } = require('ipld-dag-pb')

if (bar instanceof DAGNode) {
  // ...
}
```

..because as far as ts is concerned, `DAGNode` is actually `typeof DAGNode`
and `typeof DAGNode` has been erased since it's a `typeof` so `ipld-dag-pb`
does not export a property called `DAGNode` and kaboom.

The change here is to use the `types.d.ts` to define the `typeof` we are
exporting-but-not-really-exporting-since-it-gets-erased, use a `@typedef`
in the index file to actually export the type for use elsewhere, then rename
the `require`'d DAGNode/DAGLink classes to stop them conflicting with the
`@typedef` tag.

JS is happy, ts is happy.

Phew.
  • Loading branch information
achingbrain authored and vmx committed Mar 12, 2021
1 parent d3694e2 commit e103337
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,22 @@

const resolver = require('./resolver')
const util = require('./util')
const DAGNode = require('./dag-node/dagNode')
const DAGLink = require('./dag-link/dagLink')
const DAGNodeClass = require('./dag-node/dagNode')
const DAGLinkClass = require('./dag-link/dagLink')

/**
* @typedef {import('./types').DAGLinkLike} DAGLinkLike
* @typedef {import('./types').DAGNodeLike} DAGNodeLike
* @typedef {import('interface-ipld-format').Format<DAGNode>} DAGNodeFormat
* @typedef {import('./dag-node/dagNode')} DAGNode
* @typedef {import('./dag-link/dagLink')} DAGLink
*/

/**
* @type {DAGNodeFormat & { DAGNode: DAGNode, DAGLink: DAGLink }}
* @type {import('./types').DAGNodeFormat}
*/
module.exports = {
DAGNode,
DAGLink,
const format = {
DAGNode: DAGNodeClass,
DAGLink: DAGLinkClass,

/**
* Functions to fulfil IPLD Format interface
Expand All @@ -27,3 +28,5 @@ module.exports = {
codec: util.codec,
defaultHashAlg: util.defaultHashAlg
}

module.exports = format
8 changes: 8 additions & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import CID from 'cids'
import { Format } from 'interface-ipld-format'
import DAGNode from './dag-node/dagNode'
import DAGLink from './dag-link/dagLink'

export interface DAGLinkLike {
Hash: CID
Expand All @@ -21,3 +24,8 @@ export interface SerializableDAGNode {
Data?: Uint8Array | null
Links?: SerializableDAGLink[] | null
}

export interface DAGNodeFormat extends Format<DAGNode> {
DAGNode: typeof DAGNode
DAGLink: typeof DAGLink
}

0 comments on commit e103337

Please sign in to comment.