![](/img/trans.png)
[英]TypeChecker API: How do I find inferred type arguments to a function?
[英]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 的几种组合,但似乎没有任何效果。
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.