1

我正在使用一个用于 TS 生成的库(ts-protoc-gen),它为枚举生成以下内容:

export interface AnimalTypeMap {
    Dog: 0;
    Cat: 1;
    Fish: 2;
    Bird: 3;
}

export const AnimalType: AnimalTypeMap;
  1. 我应该如何消费它?
if (arg === AnimalType.Bird) {} // **ERROR**: Variable 'AnimalType' is used before being assigned
if (arg === AnimalTypeMap.Bird) {} // **ERROR**:'AnimalTypeMap' only refers to a type, but is being used as a value here
  1. 它如何在不初始化的情况下导出 const?
4

2 回答 2

0

如果您将 --ts-out 和 --js-out 都包含到 protoc 中,那么这对我有用:

import {AnimalType, AnimalTypeMap} from "./generated/AnimalType_pb"
const animalType:AnimalTypeMap[keyof AnimalTypeMap] = AnimalType.Bird;

但这并不完全直观,我认为这不是正确的方法。但至少它有效。

编辑:有一个叉子:https ://github.com/gnomesley/ts-protoc-gen生成正常的 TypeScript 枚举。它更直观。

于 2021-07-25T20:54:10.053 回答
0

在打字稿中更改您的枚举类,如下所示

 export interface AnimalTypeMap 
     {
    Dog: Dog;
    Cat: Cat;
    Fish: Fish;
    Bird: Bird;
     }

并在后端使用

 [JsonConverter(typeof(StringEnumConverter))]
    public enum AnimalTypeMap {
{
        Dog: 1;
        Cat: 2;
        Fish: 3;
        Bird: 4;
         }

如果你使用 C#

于 2020-07-06T07:00:34.307 回答