简体   繁体   English

枚举作为打字稿中的泛型类型

[英]enum as generic type in typescript

I would like to declare an interface with a member of type enum , as in - any enum .我想声明一个具有enum类型成员的接口,如 in-any enum The idea here is to be a little safer than saying any , but still open to future enum types.这里的想法是比说any更安全一点,但仍然对未来的enum类型开放。

Use case: I'm defining an action interface for redux, and I want the BaseAction interface to be something like this:用例:我正在为 redux 定义一个 action 接口,我希望BaseAction接口是这样的:

export interface BaseAction {
  type: enum;  //this gives an error
  payload: any;
}

Is there a way to declare that the type of a member is any so long as it's an enum ?有没有办法声明一个成员的类型是any只要它是一个enum

This way, in the future, I may define this:这样,在未来,我可能会这样定义:

export enum SpecificActionType {
  SPECIFIC_1 = "SPECIFIC_ACTION_1",
  SPECIFIC_2 = "SPECIFIC_ACTION_2",
}

export interface SpecificAction1 extends BaseAction {
  type: SpecificActionType.SPECIFIC_1;
  payload: {
    id;
  };
}

As a disclaimer, I'm all new to redux and typescript, but looking for a good rigorous and future proof paradigm that's developer friendly.作为免责声明,我是 redux 和 typescript 的新手,但正在寻找一种对开发人员友好的严格且面向未来的范例。 If you have a better idea, I'm open to that as well.如果你有更好的主意,我也愿意接受。

Basically not a generic type, but a base type.基本上不是泛型类型,而是基类型。 Unfortunately typescript does not enable you to do such a thing.不幸的是,打字稿不能让你做这样的事情。 To provide this type of extensibility you need to either:要提供这种类型的可扩展性,您需要:

Redefine the interface each time每次都重新定义接口

export interface BaseAction {
  type: SpecificActionEnum | OtherActionEnum;  
  payload: any;
}

Use the any or the unknown type.使用anyunknown类型。

You can add a generic type but can't really enforce that it has to be an enum (AFAIK).您可以添加泛型类型,但不能真正强制它必须是枚举(AFAIK)。 But the repr of an enum at least has to be a string or a number.但是枚举的 repr 至少必须是字符串或数字。

So this is really more type annotation than any sort of compile-time type checking, but it may make the code more clear:所以这确实比任何类型的编译时类型检查都更多的类型注释,但它可能使代码更清晰:

export interface BaseAction<T extends string | number> {
  type: T;
  payload: any;
}

export enum SpecificActionType {
  SPECIFIC_1 = "SPECIFIC_ACTION_1",
  SPECIFIC_2 = "SPECIFIC_ACTION_2",
}

export interface SpecificAction1 extends BaseAction<SpecificActionType> {
  type: SpecificActionType.SPECIFIC_1;
  payload: {
    id: number;
  };
}

Playground Link 游乐场链接

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

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