使用 AMD 时如何在 d.ts 文件中引用 Typescript 枚举? [英] How to refer to Typescript enum in d.ts file, when using AMD?
问题描述
我想定义一个打字稿接口来表示,比如说,一个错误.像这样:
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 变量是数字、字符串还是其他.如果你不介意字符串,你可以这样做:
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屋!