简体   繁体   中英

Typescript: enum generic Type as parameter to function

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM