我正在为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的同时导入其他导出类型吗?
谢谢。
发布于 2018-05-23 23:53:08
因此,答案实际上取决于你将如何使用类型。如果您在自己的项目中使用它们,则需要一个声明一个名为<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中添加类型(我相信他们会很感激!)您可以按照指南这里编写声明文件。
它会指给你看
您(正确地)注意到Airtable导出了一个类,这个类对TS的性能不太好。有一些讨论这里。无论哪种方式,上面的指南都将指向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
}
}https://stackoverflow.com/questions/50198579
复制相似问题