簡體   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