如何在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
相关产品推荐
相关产品推荐

