TypeScript:默认不是构造函数 [英] TypeScript: default is not a constructor

查看:297
本文介绍了TypeScript:默认不是构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的TypeScript项目中,我想使用一个名为" pure-uuid <的Node.js模块. /a>".

In my TypeScript project I want to use a Node.js module called "pure-uuid".

使用普通JavaScript,"pure-uuid"可以按以下方式使用:

With plain JavaScript, "pure-uuid" can be used as follows:

const UUID = require('pure-uuid')
const id = new UUID(4).format();

我将代码翻译成TypeScript:

I translated the code into TypeScript:

import UUID from 'pure-uuid';
const id:string = new UUID(4).format();

当我编译代码时,将生成以下内容:

When I compile the code, the following is being generated:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var pure_uuid_1 = require("pure-uuid");
var id = new pure_uuid_1.default(4).format();

不幸的是,TypeScript在引用中添加了.default,这使代码在执行时失败:

Unfortunately TypeScript adds a .default to the "pure-uuid" reference, which makes the code fail on execution:

TypeError: pure_uuid_1.default is not a constructor

我认为错误的编译是由TypeScript定义文件(已手动编写)中的错误引起的:

I think the wrong compilation is caused by a mistake in the TypeScript definition file (which has been manually written):

interface UUID {
    /*  making  */
    make(version: number, ...params: any[]): UUID;

    /*  parsing  */
    parse(str: string): UUID;

    /*  formatting  */
    format(type?: string): string;

    /*  formatting (alias)  */
    tostring(type?: string): string;

    /*  importing  */
    import(arr: number[]): UUID;

    /*  exporting  */
    export(): number[];

    /*  byte-wise comparison  */
    compare(other: UUID): boolean;
}

export interface UUIDConstructor {
  /*  default construction  */
  new(): UUID;

  /*  parsing construction  */
  new(uuid: string): UUID;

  /*  making construction  */
  new(version: number): UUID;
  new(version: number, ns: string, data: string): UUID;
}

declare var UUID: UUIDConstructor;
export default UUID;

导出"pure-uuid"模块的正确方法是什么?

What's the correct way of exporting the "pure-uuid" module?

推荐答案

尝试使用export =:

interface UUID {
  // ...
}

interface UUIDConstructor {
  /*  default construction  */
  new(): UUID;
  // ...
}

declare var tmp: UUIDConstructor;
export = tmp;

另请参见:关于export = .

See also: The documentation on export =.

然后,以下代码:

const UUID = require('pure-uuid')

…必须翻译为:

import UUID = require('pure-uuid');

这篇关于TypeScript:默认不是构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆