#How to get the inferred return type when using a return signature?

14 messages · Page 1 of 1 (latest)

pure tree
#

It's all in the title

Basically, I want to access the inferred return type from a function, while also using a type. Here's a minimal example:

cosmic wyvernBOT
#
oodavid#0

Preview:```ts
/** The Goal
*

    1. To use a type for the function
    1. To access the inferred promised return type for the function
      */
      interface CallbackParams {
      prop: string;
      }
      interface CallbackResponse {
      [key: string]: string;
      }
      type CallbackSignature = (params: CallbackParams) => Promise<CallbackResponse>;
      ...```
craggy kraken
#

you can change the declaration of the function so that it is not blocked by the generic but still meets the requirements

const myCallback = async ({ prop }:CallbackParams) => {
   return {
       hello: 'world',
       myProp: prop,
   };
}
cosmic wyvernBOT
#
m.guiu#0

Preview:ts ... const myCallback = async ({prop}: CallbackParams) => { return { hello: "world", myProp: prop, } } ...

craggy kraken
#

In this way you can obtain the type

pure tree
#

I considered that, but I want the return type to match CallbackResponse interface.

ie: this would break my code:

const myCallback = async ({ prop }:CallbackParams) => {
    return {
        hello: 'world',
        myProp: prop,
        today: new Date(), // strings only please!
        good: true, // strings only please!
    };
}
barren yarrow
#

you could use satisfies

#

this sounds like a specialized case of "check against constraint but infer more specifically"

#
const fn = () => ["a"] satisfies () => unknown[]
#

!ts fn

cosmic wyvernBOT
#
const fn: () => string[] /* 1:7 */```
pure tree
#

Thanks, @barren yarrow I'll see if I can make that work and update this thread 🙂

cosmic wyvernBOT
#

@pure tree Here's a shortened URL of your playground link! You can remove the full link from your message.

oodavid#0

Preview:```ts
/** The Goal
*

    1. To use a type for the function
    1. To access the inferred promised return type for the function
      */
      interface CallbackParams {
      prop: string;
      }

interface CallbackResponse {
[key: string]: string;
}

type CallbackSignature = (params: CallbackParams) => Promise<CallbackResponse>;
...```