【问题标题】:How to create a typings file to export a module as a class如何创建类型文件以将模块导出为类
【发布时间】:2018-04-12 05:03:15
【问题描述】:

我有一些导入messageformat 模块的Javascript 代码。这个模块可以这样使用:

const MessageFormat = require('messageformat');
const mf = new MessageFormat("en-US");
const text = mf.compile(...);

此模块导出一个类,但它没有类型文件。我创建了以下类型文件:

declare module "messageformat" {
  export class MessageFormat {
    constructor(locale: string);
    public compile(messageString: string): string;
  }
}

在我的 Typescript 代码中,我现在将其用作:

import { MessageFormat } from "messageformat";
const mf = new MessageFormat("en-US");
const text = mf.compile(...);

不幸的是,这不会生成new MessageFormat("en-US"),但会生成new messageformat_1.MessageFormat("en-US"),但会失败。我还尝试了以下方法:

declare module "messageformat" {
  export default class MessageFormat {
    constructor(locale: string);
    public compile(messageString: string): string;
  }
}

在我的 Typescript 代码中,我现在将其用作:

import MessageFormat from "messageformat";
const mf = new MessageFormat("en-US");
const text = mf.compile(...);

但这编译为new messageformat_1.default('en-US'),这也是不正确的。如何创建类型文件(以及如何导入模块)以便构造正确的类?

【问题讨论】:

  • 您的期望无效。生成的代码在各个方面都是正确的。

标签: typescript typescript-typings


【解决方案1】:

此答案基于this answer

看起来下面的方法有效:

declare module "messageformat" {
  class MessageFormat {
    constructor(locale: string);
    public compile(messageString: string): string;
  }

  export = MessageFormat;
}

不幸的是,我不能再使用import 语句了,但是下面的代码似乎可以工作:

import MessageFormat = require("messageformat");
const mf = new MessageFormat("en-US");
const text = mf.compile(...);

虽然我觉得import MessageFormat = require("messageformat") 看起来有点别扭,但它确实有效,而且所有类型都可以使用。

【讨论】:

    猜你喜欢
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多