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

如何在TypeScript中通过字符串参数创建函数生成器及自动钩子生成

问题1:实现动态键名的对象返回函数

我希望实现一个函数,传入字符串参数后返回包含该参数作为键的对象,对应的值为一个函数。我尝试了如下代码:

function getFunction(name: string): { [name]: () => number } {
  return {
    [name]: () => {
      console.log(1);
      return 2;
    },
  };
}

const { myName } = getFunction("myName");

问题2:模拟RTK Query自动生成钩子的功能

另外,RTK Query的createApi可以通过endpoints属性自动生成对应的钩子函数,我希望在TypeScript中实现类似的功能。以下是RTK Query的示例代码:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import type { Pokemon } from './types'

// 基于基础URL和预期端点定义服务
export const pokemonApi = createApi({
  reducerPath: 'pokemonApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query<Pokemon, string>({
      query: (name) => `pokemon/${name}`,
    }),
  }),
})

// 导出供函数组件使用的钩子,这些钩子基于定义的端点自动生成
export const { useGetPokemonByNameQuery } = pokemonApi

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 01:30:02