bcherny
bcherny

Reputation: 3172

How to create typings for a commonjs module with a default function export?

Here's the code I'm making a typing for:

https://github.com/jden/objectid/blob/1.1.0/index.js

What I've tried so far -

Attempt #1:

declare module "objectid" {
  interface ObjectId {
    (): string
    isValid(objectId: string): boolean
  }
  export default ObjectId
}

...
import makeObjectId from 'objectid' // Error TS2304: Cannot find name 'makeObjectId'

Attempt #2:

declare module "objectid" {
  interface ObjectId {
    (): string
    isValid(objectId: string): boolean
  }
  export = ObjectId
}

...
import makeObjectId = require('objectid')
const id = makeObjectId() // Error TS2304: Cannot find name 'makeObjectId'

Attempt #3:

declare module "objectid" {
  export default function makeObjectId(): string
  export function isValid(objectId: string): boolean
}

...
import makeObjectId = require('objectid')
const id = makeObjectId() // TypeError: objectid_1.default is not a function

EDIT: working solution for anyone that finds this in the future:

declare module "objectid" {
  interface ObjectId {
    (): string
    isValid(objectId: string): boolean
  }
  declare var objectId: ObjectId
  export = objectId
}

...
import * as makeObjectId from 'objectid'
const id = makeObjectId()

Upvotes: 0

Views: 576

Answers (1)

Amid
Amid

Reputation: 22352

You can try declaring it like this in your d.ts file:

declare module "objectid" 
{
    interface ObjectId 
    {
        (): string
        isValid(objectId: string): boolean
    }

    var foo: ObjectId;

    export default foo;
}

Upvotes: 1

Related Questions