Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
Typescript: Map object props types in wrapped function to omit certain props

I'm trying to wrap an actions object with functions as properties. Each function has an ActionContext argument.

When defining the functions the state property in the context should be accessible. But when calling the method state should not be accessible anymore, as it will be injected.

I first tried to do this with 2 separate args in each function, but that felt wrong and seemed not flexible enough. Therefor I'm using just 1 ctx argument now.

Solution approach #1: How can I dynamically re-map an object full of functions using TypeScript?

The return type on useActions = (state: any): T is ofcourse not correct, but here I want the types in the actions-object to be mapped from type Action to type CallableAction with their inferred Context-type.

But I'm struggling how to infer these types, if at all possible. Or maybe I'm just Typing too much? Quite new to typescript.

type ActionContext<S=any, P=any> = { state: S, params: P };
type Action = <T extends ActionContext>(ctx: T) => any;
type CallableActionContext<T> = T extends ActionContext ? Omit<T, 'state'> : never
type CallableAction<T=any> = (ctx: CallableActionContext<T>) => any
type SaveActionContext = ActionContext<any, {id: string}>

interface Supplier {
  name: string;
}
// add ctx types in actions
const actions = {
  save: async (ctx: SaveActionContext): Promise<Supplier> => {
    console.log('Mocked: useActions.save');
    const tralala = ctx.params.id
    await Promise.resolve(tralala)
    return {name: 's1'};
  }
}

// this is what the resulting action object should look like
// calling mapped actions and omitting `state` property):
// const save: CallableAction<SaveActionContext> = (ctx) => {
//   ctx.params.id
//   return new SupplierVM
// }
// const ret = save({params:{id: '2'}})

const createActions = <T extends Record<keyof T, Action>>(actions: T) => {
  const useActions = (state: any): T => {
    const injectCtx = (action: Action, ctx: any) => {
      const enrichedCtx = {...ctx, state: state} as ActionContext
      return action(enrichedCtx)
    }

    return Object.entries(actions).reduce((prev: any, [fnName, fn]: any) => ({
      ...prev,
      [fnName]: (ctx: any) => injectCtx(fn, ctx)
    }), {});
  }

  return useActions
}

const state = reactive({})
const useActions = createActions(actions)
const acts = useActions(state)
acts.save({params: { id: '3'}, state: {}})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Perhaps you should change (state: any): T:

const useActions = (state: any): { [K in keyof T]: CallableAction<Parameters<T[K]>[0]> } => {

We're going through each action, getting the first parameter, (SaveActionContext), then we pass that to CallableAction which gives us our desired context type.

Playground

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda