You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现TypeScript函数返回类型:为对象键追加指定字符串

问题:如何为TypeScript的addCommands函数定义正确的返回类型?

现有代码

首先是测试用的函数对象:

const testFunctions = {
   test: () => 'test',
   test2: (yo: string) => console.log('test2')
}

然后是addCommands函数,它会给原函数的键名追加前缀:

const addCommands = <N extends string, T extends Record<string, any>>(name: N, myFunctions: Readonly<T>) => {
   const commands = {};
   
   Object.keys(myFunctions).forEach((key) => {
      const commandName = `${name}_${key}`;
      commands[commandName] = myFunctions[key];
   }) // 补全原代码缺失的闭合括号

   // Cypress.Commands.addAll(commands); // 忽略该行
   return commands
}

期望效果

当调用addCommands('testing', testFunctions)时,希望返回值的类型为:

/*
{
   testing_test: () => string;
   testing_test2: (yo: string) => void
}
*/

解决方案

用TypeScript的映射类型结合模板字符串类型,就能动态生成带前缀的键名并保留原函数的类型。直接给addCommands函数指定明确的返回类型即可:

const addCommands = <N extends string, T extends Record<string, any>>(
  name: N, 
  myFunctions: Readonly<T>
): { [K in keyof T as `${N}_${K & string}`]: T[K] } => {
   const commands = {} as { [K in keyof T as `${N}_${K & string}`]: T[K] };
   
   Object.keys(myFunctions).forEach((key) => {
      const commandName = `${name}_${key}` as `${N}_${keyof T & string}`;
      commands[commandName] = myFunctions[key as keyof T];
   })

   // Cypress.Commands.addAll(commands); // 忽略该行
   return commands
}

说明

  1. { [K in keyof T as ${N}_${K & string}]: T[K] }:这是核心类型定义,遍历原对象的所有键K,用模板字符串生成新键名${N}_${K},同时保留原键对应的函数类型T[K]。K & string是为了确保K能和字符串前缀拼接(避免keyof T包含非字符串类型的情况)。
  2. 给commands变量断言为目标类型,避免TypeScript类型检查报错。
  3. 对commandName和key做类型断言,确保赋值操作符合类型要求。

内容的提问来源于stack exchange,提问作者Ewan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:05:34