【问题标题】:Typescript enums as interfacesTypescript 枚举作为接口
【发布时间】:2020-10-26 06:19:16
【问题描述】:

我正在使用一个用于 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?

【问题讨论】:

标签: typescript enums interface protobuf.js


【解决方案1】:

在 typescript 中更改您的枚举类,如下所示

 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#

【讨论】:

  • 界面是自动生成的,我无法控制
  • 如果您使用相同的代码生成器或其他代码生成器,只需在您的枚举上添加 [JsonConverter(typeof(StringEnumConverter))] 即可
  • 这是不可能的,类型是在 protobuff 文件中定义的。请假设我的第一个代码 sn-p 已给出且无法修改,您将如何在纯 TS 中使用它?
  • 使用这个:if (arg === AnimalType['Bird']) {}
【解决方案2】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2019-06-03
    • 2016-09-03
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 2019-10-18
    相关资源
    最近更新 更多