简体   繁体   English

Typescript 枚举作为接口

[英]Typescript enums as interfaces

I am using a library for TS generation (ts-protoc-gen), which generates the following for enums:我正在使用一个用于 TS 生成的库(ts-protoc-gen),它为枚举生成以下内容:

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

export const AnimalType: AnimalTypeMap;
  1. How should I consume it?我应该如何消费它?
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. How can it export a const without initializing it?它如何在不初始化的情况下导出 const?

change your enum class in typescript like bellow像下面这样在 typescript 中更改您的枚举 class

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

and in backend use并在后端使用

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

if you use c#如果您使用 c#

If you include both --ts-out and --js-out to protoc then this works for me:如果您将 --ts-out 和 --js-out 都包含在 protoc 中,那么这对我有用:

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

But it's not exactly intuitive and I don't think it's the right way to do it.但这并不完全直观,我认为这不是正确的方法。 But at least it works.但至少它有效。

EDIT: There's a fork: https://github.com/gnomesley/ts-protoc-gen that generates normal TypeScript enums.编辑:有一个叉子: https://github.com/gnomesley/ts-protoc-gen生成正常的 TypeScript 枚举。 It's much more intuitive.它更直观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM