[英]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.