且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 AMD 时如何在 d.ts 文件中引用 Typescript 枚举?

更新时间:2022-12-07 19:53:27

***解决方案可能取决于您是否更喜欢实际的 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.