Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda