Javascript 来自函数参数的动态Typescript对象属性

Javascript 来自函数参数的动态Typescript对象属性,javascript,typescript,Javascript,Typescript,我有一个函数,它接受n个参数,并生成一个新对象,其中包含参数到唯一散列的键值映射 Typescript是否有办法从函数的参数动态推断返回对象的键 例如 生成字典的CreateActionType函数: function createActionType<K extends {} | void>(...type: string[]): Readonly<{ [key: string]: string }> { const actions = {}; ty

我有一个函数,它接受n个参数,并生成一个新对象,其中包含参数到唯一散列的键值映射

Typescript是否有办法从函数的参数动态推断返回对象的键


例如

生成字典的CreateActionType函数:

function createActionType<K extends {} | void>(...type: string[]): Readonly<{ [key: string]: string }> {
    const actions = {};

    type.forEach((item: string) => {
        actions[item] = `${item}/${generateUniqueId()}`;
    });

    return Object.freeze(actions);
};

找到了使用then in关键字的解决方案

函数createActionType(…类型:K[]):{[P in K]:string}{
常量动作={};
type.forEach((项目:字符串)=>{
actions[item]=`${item}/${generateUniqueId()}`;
});
返回对象。冻结(操作)为只读;
};
使用K作为函数的参数,我们可以将返回值指定为具有包含由K定义的字符串文本的键的对象

补充阅读:

interface ActionTypes {
    MY_ACTION_1, 
    MY_ACTION_2
}

const action = createActionType<ActionTypes>("MY_ACTION_1", "MY_ACTION_2");
/*
 * action contains { MY_ACTION_1: "MY_ACTION_1/0", MY_ACTION_2: "MY_ACTION_2/1" }
 */
action.MY_ACTION_1; // returns "MY_ACTION_1/0"
const action = createActionType("MY_ACTION_1", "MY_ACTION_2");
action.MY_ACTION_1;  // Intellisense will be able to infer the properties 
                     // MY_ACTION_1 and MY_ACTION_2 from action
function createActionType<K extends string>(...type: K[]): { [P in K]: string } {
    const actions = {};

    type.forEach((item: string) => {
        actions[item] = `${item}/${generateUniqueId()}`;
    });

    return Object.freeze(actions) as Readonly<{ [P in K]: string }>;
};