简体   繁体   English

打字稿:枚举泛型类型作为函数的参数

[英]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上面的函数适用于任何statEnum: any但如果我将其更改为statEnum: typeof T它会引发错误消息

T only refers to a type, but is being used as a value here T 仅指一种类型,但在这里用作值

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.很好奇,为什么它适用于 supportedEnums 类型,但是当它添加为typeof 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:将函数参数类型更新为 T statEnum: T它在调用函数函数调用时抛出错误消息:

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

Argument of type 'typeof SVC_A' is not assignable to parameter of type 'SVC_A' “typeof SVC_A”类型的参数不可分配给“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: Playground相关问题列表:

Here you can find my article with more context and explanation在这里您可以找到我的文章,其中包含更多上下文和解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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