Reputation: 40522
How to inject Enums in 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
Upvotes: 1
Views: 557
Reputation: 20162
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.
function myfunc(Environment: Environment = _Environment.Production ): void {}
As you can see I am choosing arbitrarily one from possible values in the Enum.
You can look on Enums like on unions with static structural representation. 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
Upvotes: 0
Reputation: 383
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 {}
Upvotes: 0
Reputation: 1593
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 {}
Upvotes: 1