[英]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.下面我有两个函数
originalhelloWorld
是无类型的, helloWorld
是有类型的。 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".可以看到type o的return返回的是“推断的”返回类型(这个叫什么名字),type x返回的是“any”。
How can I have the ExampleFunction
type the functions arguments but leave the return type inferred?如何让
ExampleFunction
键入函数 arguments 但保留推断的返回类型? I've tried several combinations of generics, and nothing seems to work.我已经尝试了 generics 的几种组合,但似乎没有任何效果。
Typescript Playground 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
The new satisfies
operator in typescript 4.9 works: 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.