【问题标题】:Importing types alongside main import with import/require使用 import/require 在主导入旁边导入类型
【发布时间】:2018-05-06 10:18:14
【问题描述】:

我正在为 airtable 编写一个定义文件,不幸的是,他们只导出了一个这样的类:

...

module.exports = Airtable;

所以,我的airtable.d.ts 文件如下所示:

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

    export class Airtable {
        ...
    }

    export = Airtable;
}

当我导入 Airtable 类时效果很好:

import Airtable = require("airtable");
...
new Airtable(...)

但我也找不到导入MyType 的方法:

let a: Airtable.MyType;

导致此错误:

'Airtable' 仅指一种类型,但被用作命名空间 这里

还有:

import { MyType } from "airtable";

导致这些错误:

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

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

【问题讨论】:

    标签: typescript types airtable


    【解决方案1】:

    所以答案实际上取决于您将如何使用这些类型。如果您在自己的项目中使用它们,则需要一个文件(称为<whatever>.d.ts)来声明一个名为"airtable" 的模块。在那,你需要导出一些东西。由于您要导出一个类,因此您必须使用export = X 语法而不是export X,因为您要更改整个导出对象而不是添加属性。在导出对象上(稍后会详细介绍)。至于类型,在您的.d.ts 文件中的模块之外,您还可以decalre 将成为全局可用的类型。如果这让您感到不适(或者您担心冲突),您也可以将您的类型放入模块中。由于它是一个纯打字稿,它不需要任何 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 添加类型(我相信他们会很感激!)您可以按照指南here 来编写声明文件。

    它会指向你

    您(正确地)注意到 Airtable 导出了一个类,它不能很好地与 TS 配合使用。有一些讨论here。无论哪种方式,上面的指南都会将您指向module-class.d.ts,它允许您声明一个导出的类和伴随的类型。您不能在上面使用它,因为该格式仅在定义文件位于模块根目录或 @types/<module> 时可用。

    /*~ 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
      }
    }
    

    【讨论】:

    • 我终于重新开始处理这个问题,我选择了AirtableTypes 模块解决方案。这有点粗略,但它很快而且有效。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2021-12-27
    • 2019-04-16
    • 2022-10-05
    • 2016-12-24
    • 2013-07-11
    • 1970-01-01
    相关资源
    最近更新 更多