使用AMD时,如何在d.ts文件中引用Typescript枚举? [英] How to refer to Typescript enum in d.ts file, when using AMD?

查看:986
本文介绍了使用AMD时,如何在d.ts文件中引用Typescript枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个打字稿接口来表示一个错误.像这样:

I want to define a typescript interface to represent, say, an error. Something like this:

enum MessageLevel {
    Unknown,
    Fatal,
    Critical,
    Error,
    Warning,
    Info,
    Debug
}

interface IMyMessage {
    name: string;
    level: MessageLevel;
    message: string;
}

此功能可以正常运行.但是,现在(也许)我想在.d.ts文件中声明该接口,以便其他人可以使用该接口进行键入.但是我不想在.d.ts文件中定义枚举,因为那将是实现而不是简单的键入信息.枚举应该在一个.ts文件中,我们称其为messageLevel.ts:

This works fine as far as it goes. However, now (perhaps) I want to declare that interface in a .d.ts file so others can use it for typing. But I don't want to define the enum in the .d.ts file, since that would be implementation and not simple typing information. The enum should presumably be in a .ts file, let's call it messageLevel.ts:

///<amd-module name='MessageLevel'/>

export enum MessageLevel {
    Unknown,
    Fatal,
    Critical,
    Error,
    Warning,
    Info,
    Debug
}

现在,我可以通过以下方式在d.ts输入文件中使用它:

and I can, at this point, use it in my d.ts typing file this way:

import * as ml from "./MessageLevel";

interface IMyMessage {
    name: string;
    level: ml.MessageLevel;
    message: string;
}

,我可以完成这项工作,但是我不喜欢将实现文件导入到键入文件中的级别混合.我也不喜欢在类型文件中实际实现枚举的想法.

and I can make this work, but I don't like the level-mixing of importing an implementation file into a typing file. Nor do I like the idea of actually implementing an enum in a typings file.

是否有一种干净的方法可以将实现和声明严格分开?

Is there a clean way to do this that keeps implementation and declaration strictly separate?

推荐答案

最佳解决方案可能取决于您是否对实际的JavaScript变量(数字,字符串或其他)有偏好.如果您不介意String,则可以这样做:

The best solution may depend on whether you have a preference for the actual JavaScript variable being a number, a string, or otherwise. If you don't mind String, you can do it like this:

///messagelevel.d.ts
export type MessageLevel = "Unknown" | "Fatal" | "Critical" | "Error";



///main.d.ts
import * as ml from "./MessageLevel";

interface IMyMessage {
    name: string;
    level: ml.MessageLevel;
    message: string;
}

因此,在最后的JavaScript中,它将简单地表示为字符串,但是只要您将它与不在该列表中的值进行比较,或者尝试将其分配给其他字符串,TypeScript都会标记一个错误.由于这是JavaScript本身最接近任何枚举(例如document.createElement("video")而不是document.createElement(ElementTypes.VIDEO)的枚举),因此它可能是表达此逻辑的更好方法之一.

So in the end JavaScript, it will simply be represented as a string, but TypeScript will flag an error anytime you compare it to a value not in that list, or try to assign it to a different string. Since this is the closest that JavaScript itself has to any kind of enum (eg, document.createElement("video") rather than document.createElement(ElementTypes.VIDEO), it might be one of the better ways of expressing this logic.

这篇关于使用AMD时,如何在d.ts文件中引用Typescript枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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