如何从 Typescript 中的界面创建枚举

问题描述 投票:0回答:1

我正在使用用 Typescript 编写的 Parse Server 构建后端。 Parse 在很多地方使用“魔术字符串”,我试图避免它们。

例如,如果我有一个名为

Item
的解析类,并且它有一个属性
color
,我将通过以下方式获取该属性:
myItem.get('color')

我希望使这种类型安全,并使用枚举来表示

color
而不是字符串本身。我已经为
Item
的所有属性定义了一个接口,如下所示:

import { Attributes, Object } from 'parse'

export interface ItemAttributes extends Attributes {
  color: string
  size: number
  enabled: boolean
}

export class Item extends Object<ItemAttributes> {
  constructor (data?: Partial<ItemAttributes>) {
    super('Item', data as ItemAttributes)
  }
}

有没有一种方法可以从 Typescript 中的

ItemAttributes
接口生成枚举,而不必像这样为每个 Parse 类创建一个新的枚举?

export enum ItemKeys {
  color = 'color'
  size = 'size'
  enabled = 'enabled'
}

因此,我希望能够在 Parse getter 中使用我的新枚举,如下所示:

myItem.get(ItemKeys.color)
node.js typescript types enums parse-platform
1个回答
0
投票

您可以使用 TS-morph 生成枚举

文档缺乏,使用起来不太方便 而且大部分都是字符串操作 所以不适合胆小的人

您可以使用 chatGPT 生成您需要的确切代码

有了它你可以做这样的事情:

        keyValueEnum = enumFile.addEnum({
            name: keyValueEnumName,
            isExported: true,
        });
        keyValueEnum.addMember({
            docs: ['some teext formatted with JS Docs'],
            name: key,
            value: 'A String you want the Value to be',
        });
© www.soinside.com 2019 - 2024. All rights reserved.