How to infer return type of a property function as the type of a property?

Viewed 446

Is there a way in typescript to get the return type of a object property function and use that as the type of another object property function's parameter?

For example:

const request = {
  
  // Infer the return type of this data function as shown to below...
  data: () => ({ people: ["bob", "jack"] }),

  // The type of `data` parameter should now be an object with people as a prop with the type of string[].
  run: (data) => Promise.resolve(data.people),
  
}

I'm not even sure if this is possible, but the closest I've got is the following...

interface IRequest<TDataProps = {}> {
  data: () => TDataProps,
  run: <TReturnRun>(data: TDataProps) => MaybePromise<TReturnRun>;
}

// So can manually provide the type but not inferred...
const request: IRequest<{ people: string[] }> = {
  data: () => ({ people: ["bob", "jack"] }),
  run: (data) => Promise.resolve(data.people),
}

Many thanks

1 Answers

You can't use the IRequest type without a type parameter, unless you want it to use the default type of {} due to you having <TDataProps = {}>.

But what you can do is define a type that you can then use in a function to infer the correct types for the generic type parameters.

Like so:

interface IRequest<TDataProps, TReturnRun> {
  data: () => TDataProps,
  run: (data: TDataProps) => MaybePromise<TReturnRun>;
}

// The simplest example of a function that can correctly infer the types.
const makeRequest = <TDataProps, TReturnRun>(request: IRequest<TDataProps, TReturnRun>) => request;

// Now you can use this function to avoid having to specify the types.
const request = makeRequest({
  data: () => ({ people: ["bob", "jack"] }),
  run: (data) => Promise.resolve(data.people),
});

Playground link

Related