简体   繁体   中英

How do I type a function's arguments but leave the return type "inferred"?

Below I have two functions originalhelloWorld which is untyped and helloWorld which has a type. You can see that the return of type o returns the "inferred" return type (what is the name for this), and type x returns "any".

How can I have the ExampleFunction type the functions arguments but leave the return type inferred? I've tried several combinations of generics, and nothing seems to work.

Typescript Playground

const originalhelloWorld = (greeting: string | boolean) => {
   if (typeof greeting === 'boolean') return greeting
   return `hello ${greeting}`
}

type o = ReturnType<typeof originalhelloWorld>
//  ^? type o = string | boolean

/* ------------------------------------ */

type ExampleFunction = (greeting: string | boolean) => any

const helloWorld: ExampleFunction = (greeting) => {
   if (typeof greeting === 'boolean') return greeting
   return `hello ${greeting}`
}

type x = ReturnType<typeof helloWorld>
//  ^? type x = any

The new satisfies operator in typescript 4.9 works:

Playground Link:

const originalhelloWorld = (greeting: string | boolean) => {
   if (typeof greeting === 'boolean') return greeting
   return `hello ${greeting}`
}

type o = ReturnType<typeof originalhelloWorld>
//  ^?

/* ------------------------------------ */

type ExampleFunction = (greeting: string | boolean) => any

const helloWorld = ((greeting) => {
   if (typeof greeting === 'boolean') return greeting
   return `hello ${greeting}`
}) satisfies ExampleFunction

type x = ReturnType<typeof helloWorld>
//  ^?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM