【问题标题】:Typescript: using an enum declared in another file打字稿:使用在另一个文件中声明的枚举
【发布时间】:2016-10-15 20:08:05
【问题描述】:

假设我在一个文件 (test1.ts) 中声明了一个枚举:

export enum Colors{
    red=1,
    blue=2,
    green=3
}

然后在另一个文件 (test2.ts) 中,我声明了一个具有方法的类。该方法的参数之一是在 Colors 枚举中定义的 Color:

'use strict';
declare var require: any;
declare var exports: any;

var Colors = require('Colors');

class DoSomethingWithColor{
    ColorFunction(aColour:Colors){
        //Funky color processing here..
    }
}

但是,我收到一个错误:

不能为颜色命名

即使它在第二个文件中导出并需要。 我在这里做错了什么,或者这只是不是一种“打字”的方式来做我想做的事情(如果是这样,首选的方式是什么?)?

谢谢

【问题讨论】:

  • import { Colors } from './test1';?
  • 嗯...好吧,这很好。我应该什么时候使用导入,什么时候需要?
  • 一般使用import,但此答案有效的原因是它使用{Colors} 而不仅仅是Colors。前者适用于export,后者适用于export default
  • @jonrsharpe:如果您将此作为答案发布,我将接受它以结束问题:)

标签: typescript enums


【解决方案1】:

正如 jonrsharpe 在 cmets 中提到的,您必须使用 typescript 支持的 import 语句之一。

import * from './test1' as Colors

import {Colors} from './test1'

有关 typescript 中关于模块(现在的命名空间)的导入语句和最佳实践的更多信息,请查看他们的文档:https://www.typescriptlang.org/docs/handbook/modules.htmlhttps://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html

通常,如果您使用导出/导入语句,则需要像 CommonJSWebPack 这样的模块加载器。这些程序捆绑您的代码,并负责确保导入程序在运行时可以使用依赖项。从 import 语句开箱即用的事实来看,您很可能已经在使用模块加载器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-29
    • 2021-11-10
    • 2020-01-29
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 2023-04-11
    • 2020-04-30
    相关资源
    最近更新 更多