#How to get the inferred return type when using a return signature?
14 messages · Page 1 of 1 (latest)
Preview:```ts
/** The Goal
*
-
- To use a type for the function
-
- 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>;
...```
- To access the inferred promised return type for the function
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,
};
}
Preview:ts ... const myCallback = async ({prop}: CallbackParams) => { return { hello: "world", myProp: prop, } } ...
In this way you can obtain the type
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!
};
}
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
const fn: () => string[] /* 1:7 */```
Thanks, @barren yarrow I'll see if I can make that work and update this thread 🙂
Thanks again, all sorted.
I had to wrap the function declaration in (parenthesis) in order to add the satisfies statement.
Here's my final code:
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@pure tree Here's a shortened URL of your playground link! You can remove the full link from your message.
Preview:```ts
/** The Goal
*
-
- To use a type for the function
-
- To access the inferred promised return type for the function
*/
interface CallbackParams {
prop: string;
}
- To access the inferred promised return type for the function
interface CallbackResponse {
[key: string]: string;
}
type CallbackSignature = (params: CallbackParams) => Promise<CallbackResponse>;
...```