gpt4 book ai didi

node.js - 将枚举与 TypeScript 结合使用,并在每个枚举上使用方法

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:10 26 4
gpt4 key购买 nike

我有这个 TypeScript 文件:

export type TSumanToString = () => string;

export interface ISumanEvent {
explanation: string,
toString: TSumanToString
}

export interface ISumanEvents{
[key: string]: ISumanEvent
}

export const events: ISumanEvents = Object.freeze({

// runner events
TEST_FILE_CHILD_PROCESS_EXITED: {
explanation: 'runner is started, fires before any test child processes are started.',
toString: makeToString('TEST_FILE_CHILD_PROCESS_EXITED')
},

RUNNER_EXIT_CODE: {
explanation: 'runner is started, fires before any test child processes are started.',
toString: makeToString('RUNNER_EXIT_CODE')
},

RUNNER_EXIT_SIGNAL: {
explanation: 'runner is started, fires before any test child processes are started.',
toString: makeToString('RUNNER_EXIT_SIGNAL')
},

RUNNER_HIT_DIRECTORY_BUT_NOT_RECURSIVE: {
explanation: 'runner is started, fires before any test child processes are started.',
toString: makeToString('RUNNER_HIT_DIRECTORY_BUT_NOT_RECURSIVE')
},

RUNNER_EXIT_CODE_IS_ZERO: {
explanation: 'runner is started, fires before any test child processes are started.',
toString: makeToString('RUNNER_EXIT_CODE_IS_ZERO')
},

RUNNER_TEST_PATHS_CONFIRMATION: {
explanation: 'runner is started, fires before any test child processes are started.',
toString: makeToString('RUNNER_TEST_PATHS_CONFIRMATION')
},

// there are a lot more entries

})

这会生成一个 .d.ts 文件,如下所示:

export declare type TSumanToString = () => string;
export interface ISumanEvent {
explanation: string;
toString: TSumanToString;
}
export interface ISumanEvents {
[key: string]: ISumanEvent;
}
export declare const events: ISumanEvents;

但我需要将事件的每个属性作为常量或枚举包含在内。我可以使用一个界面来做到这一点,但这需要我复制所有内容,这看起来很浪费。

换句话说,我不想这样做,因为这只是重复了我的 const 中的内容,这是一种浪费,并且很容易变得不同步:

export interface ISumanEvents {

TEST_FILE_CHILD_PROCESS_EXITED: ISumanEvent,
RUNNER_EXIT_CODE: ISumanEvent,
RUNNER_EXIT_SIGNAL: ISumanEvent,
RUNNER_HIT_DIRECTORY_BUT_NOT_RECURSIVE: ISumanEvent;
RUNNER_EXIT_CODE_IS_ZERO: ISumanEvent,
RUNNER_TEST_PATHS_CONFIRMATION: ISumanEvent

}

有没有办法创建一个枚举,这样我就不必创建一个只复制实际对象中所有内容的接口(interface)?

问题是我不知道如何在枚举上定义方法。

最佳答案

是否有原因导致您无法使用内置的 Typescript 枚举?

http://www.typescriptlang.org/docs/handbook/enums.html

关于node.js - 将枚举与 TypeScript 结合使用,并在每个枚举上使用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44917345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com