常量值的Typescript通用参数

常量值的Typescript通用参数,typescript,Typescript,是否可能有一个接受泛型参数的常量值 对于此代码 import*as R从'ramda'; 枚举ApiActionType{ 请求, 完整的, 失败, 取消, } 类型ApiActionTypeKeys=类型ApiActionType的键; 枚举ChangedActionType{ 改变, } 类型ChangedActionTypeKeys=类型为ChangedActionType的键; 常量getActionType=( 按键:TActionTypeKeys[] ) => ( 前缀:TPrefi

是否可能有一个接受泛型参数的常量值

对于此代码

import*as R从'ramda';
枚举ApiActionType{
请求,
完整的,
失败,
取消,
}
类型ApiActionTypeKeys=类型ApiActionType的键;
枚举ChangedActionType{
改变,
}
类型ChangedActionTypeKeys=类型为ChangedActionType的键;
常量getActionType=(
按键:TActionTypeKeys[]
) => (
前缀:TPrefix
):记录=>{
回油管(
R.map(k=>[k,[prefix,k]]as[TActionTypeKeys,[TPrefix,TActionTypeKeys]],
R.fromPairs as()=>记录
)(钥匙);
}
//const createApiationType:(前缀:TPrefix)=>记录
const createApiationType=(前缀:TPrefix)=>getActionType(R.keys(ApiationType))(前缀)
//const createChangedChionType:(前缀:TPrefix)=>记录
const createChangedActionType=(前缀:TPrefix)=>getActionType(R.keys(ChangedActionType))(前缀)
是否可以将最后两行简化到下面,而不丢失结果函数的泛型参数?i、 e.保留
TPrefix
泛型参数,而不是成为前缀类型为
unknown
的非泛型函数

//const createApiActionType:(前缀:未知)=>记录
const createApiationType=getActionType(R.keys(ApiationType))
//常量createChangedctionType:(前缀:未知)=>记录
const createChangedActionType=getActionType(R.keys(ChangedActionType))

给定一个当前的
getActionType
函数声明

declare const getActionType: <TPrefix, TActionTypeKeys extends string>(
  keys: TActionTypeKeys[]
) => (
    prefix: TPrefix
  ) => Record<TActionTypeKeys, [TPrefix, TActionTypeKeys]>
我们可以通过在内部函数上定义
TPrefix
来解决这个问题

declare const getActionType: <TActionTypeKeys extends string>(
    keys: TActionTypeKeys[]
) => <TPrefix>(prefix: TPrefix) => Record<TActionTypeKeys, [TPrefix, TActionTypeKeys]>
declare const getActionType:(
按键:TActionTypeKeys[]
)=>(前缀:TPrefix)=>记录
并测试它:

declare const apiActionTypeKeys: ApiActionTypeKeys[]
declare const changedActionTypeKeys: ChangedActionTypeKeys[]

// <TPrefix>(prefix: TPrefix) => Record<ApiActionTypeKeys, [TPrefix, ApiActionTypeKeys]>
const createApiActionType = getActionType(apiActionTypeKeys)

// "requested" | "completed" | "failed" | "cancelled"
const result = createApiActionType("fooPrefix").cancelled[1]
declare const apiActionTypeKeys:apiActionTypeKeys[]
声明常量changedActionTypeKeys:changedActionTypeKeys[]
//(前缀:TPrefix)=>记录

希望有帮助

看起来与……有关。我怀疑在打字脚本中不存在可变类型
declare const apiActionTypeKeys: ApiActionTypeKeys[]
declare const changedActionTypeKeys: ChangedActionTypeKeys[]

// <TPrefix>(prefix: TPrefix) => Record<ApiActionTypeKeys, [TPrefix, ApiActionTypeKeys]>
const createApiActionType = getActionType(apiActionTypeKeys)

// "requested" | "completed" | "failed" | "cancelled"
const result = createApiActionType("fooPrefix").cancelled[1]