3

I have this enum

enum methods {
  DELETE = 1,
  POST,
  PUT,
  GET
}

I want to have a function accepting a parameter that can be one of the keys of the methods enum.

const getMethodPriority = (method /* how do I type this? */) => {
  return methods[method];
};

so, for example getMethodPriority("DELETE") would return 1.

How do I type the method parameter?

1
  • You can go with (method: keyof typeof methods) Commented Feb 20, 2018 at 7:46

2 Answers 2

12

You can directly obtain numbers from numeric enums by converting their values to number:

enum methods {
    DELETE = 1,
    POST = 2,
    PUT = 3,
    GET = 4
}

let enumPriority = methods.DELETE as number;
// enumPriority == 1

But if you really want to have a method for this you can:

enum methods {
    DELETE = 1,
    POST = 2,
    PUT = 3,
    GET = 4
}

const getMethodPriority = (method: keyof typeof methods) => {
    return methods[method];
};

// how to call
getMethodPriority("DELETE");
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry!! methodPriorities was supposed to be just methods. please see my updated getMethodPriority function
if so - you don't need any function - just convert to number as I wrote in PS section.
As an added bonus of using the keyof typeof combination, you can also do type checking of compound enums, such as a dot-separated path string that gets unpacked later like 'property.subprop.field' - that's not possible with a direct enum reference.
0

Use the keyof and typeof operators like this:

enum methods {
  DELETE = 1,
  POST,
  PUT,
  GET
}

const getMethodPriority = (method: keyof typeof methods) => {
    return methods[method];
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.