1

i have a function which takes two parameters one is a key and other is an enum type. I am trying to generalize this function with strong typing to take any enum type and return the value:

export const getStatus = <T>(key: string, statEnum: any): string => {
 return statEnum(key);
}

function call:

console.log(getStatus<SVC_A>('AUTH_122', SVC_A));

This above function works with paramater typed as any statEnum: any but if I change it to statEnum: typeof T it throws an error message

T only refers to a type, but is being used as a value here

Parameter typing works if I add in a variable

type supportedEnums = typeof SVC_A | typeof SVC_B
export const getStatus = <T>(key: string, statEnum: supportedEnums): string => {
 return statEnum(key);
}

curious to understand, why it works with supportedEnums type but when it's added as typeof T it doesn't.

i also tried it as

export const getStatus = <T>(key: string, statEnum: T): string => {
 return statEnum(key);
}

updated function parameter type to T statEnum: T it thorws error message while calling the function function call:

console.log(getStatus<SVC_A>('AUTH_122', SVC_A));

Argument of type 'typeof SVC_A' is not assignable to parameter of type 'SVC_A'

Is there a possibility to define an enum as a parameter and typesafe?

3
  • please provide reproducible example Commented Jun 5, 2022 at 10:26
  • playcode.io/908185 Commented Jun 5, 2022 at 22:03
  • once you do any changes(placing semicolon) in the above link, it will show the error message "Argument of type 'typeof SVC_A' is not assignable to parameter of type 'SVC_A'" . In the playground parameter type is set to type T Commented Jun 5, 2022 at 22:06

1 Answer 1

2

First of all, you dont need to use explicit generic parameter. Consider this example:

enum SVC_A {
    INVALID = 'INVALID',
    YENNA = 'YENNA',
    AUTH_122 = 'AUTH FAILED',
}

type PseudoEnum = Record<string | number, string | number>


function getStatus<Enum extends PseudoEnum, Key extends keyof Enum>(statEnum: Enum, key: Key) {
    return statEnum[key];
};

const foo = getStatus(SVC_A, 'YENNA') // SVC_A.YENNA

Playground List of related questions:

Here you can find my article with more context and explanation

Sign up to request clarification or add additional context in comments.

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.