Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!