Michael Hancock
Michael Hancock

Reputation: 2855

Type define an Enum in TypeScript

I have a TypeScript Enum that lives within a different namespace to the file I am trying to use it in. The namespace for now unavoidable reasons is long and cumbersome to write

The project is not using modules and does not have a module loader so no imports or exports. My hands are tied here unfortunately. We bundle files manually.

enum Movement {
    run,
    walk
}
function Move(movement: App.System.User.Area.Movement) { 
    if (movement === App.System.User.Area.Movement.run) { //... }
    //....
}

I am able to use it seems the type keyword to (and I am not sure this is the TypeScript word for it) type def that long namespace away.

type MovementType = App.System.User.Area.Movement;
function Move(movement: MovementType) { 
    if (movement === App.System.User.Area.Movement.run) { //... }
    //....
}

But I cannot use that type def'd type in the equals comparison in my function above because "MovementType only refers to a type but is being used as a value here" when I try to do:

type MovementType = App.System.User.Area.Movement;
function Move(movement: MovementType) { 
    if (movement === MovementType.run) { //... }
    //....
}

Is there any way to get around this? Why can't I use it in the conditional statement while I can have it as a parameter? How can I get around my very long namespace?


I am currently using TypeScript 3.1

Upvotes: 2

Views: 1211

Answers (2)

Keen
Keen

Reputation: 36

As Pac0 mentioned, an enum is both a set of values and a type. If the import solution doesn't work for you, you could try aliasing both the type and value.

type MovementType = App.System.User.Area.Movement;
const Movement = App.System.User.Area.Movement;
function Move(movement: MovementType) { 
    if (movement === Movement.run) { //... }
    //....
}

Example on TypeScript Playground

Upvotes: 1

Pac0
Pac0

Reputation: 23174

The type keyword is indeed only creating an alias for the type that is defined by the enum, it can't work to access the values of the enum (hence, the explicit error messages).

You can achieve something similar to what you want by aliasing the long namespace with import :

import area = App.System.User.Area;

function Move(movement: area.Movement) { 
    if (movement === area.Movement.run) { //... }
    //....
}

That should at least help a bit.

More info in TypeScript docs.

Example on TypeScript playground

Upvotes: 0

Related Questions