[英]How to inject Enums in TypeScript?
How to inject Enums in TypeScript? 如何在TypeScript中注入枚举? Is this possible and recommended?
这可能并建议吗?
enums.ts: 枚举:
export enum Environment {
Development = 'Development',
Production = 'Production',
Test = 'Test'
}
file: 文件:
import { Environment as _Environment } from '../enums';
function myfunc(Environment: Environment = _Environment): void {}
I get: 我得到:
application/libs/config/index.ts:23:18 - error TS2749: 'Environment' refers to a value, but is being used as a type here.
23 Environment: Environment = _Environment
This works fine 这很好
function myfunc(Environment: _Environment): void {}
However, if you want to utilize default parameters you can try something like this 但是,如果要使用默认参数,可以尝试执行以下操作
function myfunc(Environment: _Environment = _Environment.Development): void {}
Enum is kind of union/variant type. 枚举是一种并集/变量类型。 It means that it defines group of possible values, but is not a value itself.
这意味着它定义了一组可能的值,但本身不是值。 Your function has an argument of type
Environment
, and it means that you can assign one of possible value existing in the enum Enviroment
, but not Enum itself as you try to do, as Enviroment
itself is not a value but a type. 您的函数的参数类型为
Environment
,这意味着您可以分配枚举Enviroment
存在的可能值之一,但不能像尝试那样分配Enum本身,因为Enviroment
本身不是值而是一种类型。
function myfunc(Environment: Environment = _Environment.Production ): void {}
As you can see I am choosing arbitrarily one from possible values in the Enum. 如您所见,我正在从Enum中的可能值中任意选择一个。
You can look on Enums like on unions with static structural representation . 您可以像使用具有静态结构表示的联合一样查看Enums。 It means that:
代表着:
type T = 'a' | 'b';
enum TEnum {
a = 'a'
b = 'b'
}
// using
const a: T = 'a' // direct setting the value
const b: TEnum = TEnum.b // using existing enum structure to set the value
This is how you would do it. 这就是您要做的。 Default envoronment being Development.
默认环境为开发中。
export enum Environment {
Development = 'Development',
Production = 'Production',
Test = 'Test'
}
function myfunc(e: Environment = Environment.Development): void {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.