如何使用默认函数导出为 commonjs 模块创建类型

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

本文关键字:commonjs 模块 创建 类型 何使用 默认 函数      更新时间:2023-09-26

这是我正在为其键入的代码:

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

到目前为止我尝试过的 -

尝试 #1:

declare module "objectid" {
  interface ObjectId {
    (): string
    isValid(objectId: string): boolean
  }
  export default ObjectId
}
...
import makeObjectId from 'objectid' // Error TS2304: Cannot find name 'makeObjectId'

尝试#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'

尝试 #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

编辑:任何将来发现这一点的人的工作解决方案:

declare module "objectid" {
  interface ObjectId {
    (): string
    isValid(objectId: string): boolean
  }
  declare var objectId: ObjectId
  export = objectId
}
...
import * as makeObjectId from 'objectid'
const id = makeObjectId()

您可以尝试在 d.ts 文件中像这样声明它:

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