下面我有两个函数originalhelloWorld
,它是非类型的,helloWorld
是有类型的。您可以看到,类型o的返回返回"0";推断的";返回类型(这个名称是什么(,并且类型x返回"0";任何";。
如何让ExampleFunction
键入函数参数,而不推断返回类型?我尝试了几种泛型组合,但似乎都不起作用。
打字游戏场
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>
// ^?