繁体   English   中英

如何键入函数的 arguments 但保留返回类型“推断”?

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

下面我有两个函数originalhelloWorld是无类型的, helloWorld是有类型的。 可以看到type o的return返回的是“推断的”返回类型(这个叫什么名字),type x返回的是“any”。

如何让ExampleFunction键入函数 arguments 但保留推断的返回类型? 我已经尝试了 generics 的几种组合,但似乎没有任何效果。

Typescript 游乐场

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

typescript 4.9 工程中的新satisfies运算符:

游乐场链接:

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>
//  ^?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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