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

194
Visualizações
How to declare an optional generic type in an function props?

I want to create something similar to createAction from redux-toolkit. I need to pass a payload type to createAction, but I don't understand how to make an optional property mandatory if it was passed.

Here is my implementation.

type ActionFormat<P = undefined> = {type: string} & (P extends undefined ? {} : {payload: P})

export function createAction<P = undefined>(type: string): (payload?: P) => ActionFormat {
  const actionCreator = (payload?: P) => ({ type, payload: payload });
  return actionCreator;
}

Creation of actions

 const startFetch = createAction('START_FETCH');
 const successFetch = createAction<number>('SUCCESS_FETCH')

Run actions

startFetch(); //there are no errors. No payload required 
startFetch('test'); //must be an error Payload has been submitted
successFetch(); //must be an error Payload was not submitted
successFetch(123); // there are no errors.
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a conditional type to spread a tuple type to a rest parameter, making the parameter either required or not based on whether P extends undefined (ie is undeinfed or a union containing undefined)

export function createAction<P = undefined>(type: string): (...payload: 
  P extends undefined 
      ? [payload?: P] // P === undefined, no parameters required, but pay be passed in.
      : [payload: P] //P does not contain undefined parameter is required
  ) => ActionFormat {
  const actionCreator = (payload?: P) => ({ type, payload: payload });
  return actionCreator;
}

Playground Link

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