Typescript 使用导入/要求与主导入一起导入类型

Typescript 使用导入/要求与主导入一起导入类型,typescript,types,airtable,Typescript,Types,Airtable,我正在为airtable编写一个定义文件,不幸的是,他们只导出一个类,如下所示: ... module.exports = Airtable; declare module "airtable" { export type MyType = { ... }; export class Airtable { ... } export = Airtable; } 因此,我的airtable.d.ts文件如下所示: ... module.ex

我正在为airtable编写一个定义文件,不幸的是,他们只导出一个类,如下所示:

...

module.exports = Airtable;
declare module "airtable" {
    export type MyType = { ... };

    export class Airtable {
        ...
    }

    export = Airtable;
}
因此,我的airtable.d.ts文件如下所示:

...

module.exports = Airtable;
declare module "airtable" {
    export type MyType = { ... };

    export class Airtable {
        ...
    }

    export = Airtable;
}
导入Airtable类时效果非常好:

import Airtable = require("airtable");
...
new Airtable(...)
但我也找不到导入MyType的方法:

导致此错误的原因:

“Airtable”仅引用类型,但用作命名空间 这里

以及:

导致这些错误的原因:

模块airtable没有导出的成员“MyType” 模块airtable解析为非模块实体,无法使用此构造导入

知道如何在继续使用export=和import/require的同时导入其他导出类型吗?
谢谢。

所以答案实际上取决于您将如何使用这些类型。如果您在自己的项目中使用它们,则需要一个名为.d.ts的文件来声明一个名为airtable的模块。在这种情况下,您需要导出一些内容。由于要导出类,因此必须使用export=X语法而不是export X,因为您要更改整个导出对象,而不是添加属性。在导出对象上,请稍后详细介绍。至于类型,在.d.ts文件的模块之外,您还可以标记一个将成为全局可用的类型。如果这让你感觉不对劲,或者你担心冲突,你也可以将你的类型放入模块中。因为它是唯一的类型脚本,所以不需要任何js代码的支持。然后,您可以像平常一样导入/导出它:

// my.d.ts

declare module 'airtable' {
  class Airtable {
    constructor(opts?: MyType)
  }
  export = Airtable
}

declare type MyType = string | number

declare module 'AirtableTypes' {
  export type MyString = string
  export type MyNumber = number
}
用法

// index.ts
import Airtable from 'airtable'
import AirtableTypes from 'AirtableTypes'

const a = new Airtable('a')

const n: MyType = 3

const s: AirtableTypes.MyString = '3'
如果你想给DefinitelyTyped添加类型,我相信他们会很感激的!您可以按照指南编写声明文件

它会指向你

您正确地注意到,Airtable只导出一个类,而这并不能很好地与TS配合使用。不管是哪种方式,上面的指南都会告诉您,它允许您声明导出的类和附带的类型。您无法使用上述格式,因为该格式仅在定义文件位于模块根目录或@types/中时可用


我终于重新开始处理这个问题,我使用了AirtableTypes模块解决方案。这有点粗略,但它很快,它的工作。谢谢
/*~ This declaration specifies that the class constructor function
 *~ is the exported object from the file
 */
export = Airtable

/*~ Write your module's methods and properties in this class */
declare class Airtable {
  constructor(opts?: Airtable.AirtableMethodOptions)
}

/*~ If you want to expose types from your module as well, you can
 *~ place them in this block.
 */
declare namespace Airtable {
  export interface AirtableMethodOptions {
    endpointUrl: string
  }
}