Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference fails for function accepting function with object argument #36020

Closed
staeke opened this issue Jan 6, 2020 · 5 comments
Closed
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@staeke
Copy link

staeke commented Jan 6, 2020

TypeScript Version: 3.7.x-dev.201xxxxx
3.7.4

Search Terms:
inference

function func(arg: {foo:1, bar: 1}) {}

// 1. Fails
giveMeAFunc(func)
// 2. Succeeds
giveMeAFunc<{foo: 1, bar: 1}, typeof func>(func)

function giveMeAFunc<TArg extends {foo:1}, TFn extends (t:TArg) => void>(fn:TFn) {}

Expected behavior:
I'd expect TS to infer the type arguments in case 1 (to be case 2)

Actual behavior:
Fails with message that bar is a missing property

Playground Link:
Couldn't find a "Share" button

Related Issues:
not really

@staeke
Copy link
Author

staeke commented Jan 6, 2020

I should probably add another comment:

Why not just type giveMeAFunc like this then?

function giveMeAFunc<TArg extends {foo:1}>(fn:(t:TArg) => void) {}

While that works, I want to use the exact type of the function for parts of the return type in my real world example. Something like

function giveMeAFunc<TArg extends {foo:1}, TFn extends (t:TArg) => void>(fn:TFn):TFn {
  return null as any
}

@staeke
Copy link
Author

staeke commented Jan 6, 2020

That said - I realized that this works

function giveMeAFunc<TArg extends {foo:1}, TFn>(fn:TFn & ((t:TArg) => void)):TFn {
  return null as any
}

Why? And also, isn't the original issue still valid?

@RyanCavanaugh
Copy link
Member

See #30134.

Ultimately you have "too many" type parameters and this is not the best way to write the function declaration.

@RyanCavanaugh RyanCavanaugh added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Jan 6, 2020
@staeke
Copy link
Author

staeke commented Jan 7, 2020

@RyanCavanaugh ok, thanks. Is there a better way, that allows me to:

  • keep the type of the passed function for return type (names of arguments for instance)
  • require that the function is accepting one object argument with a property foo

?

@RyanCavanaugh
Copy link
Member

Not really, since what you're describing is both an upper and lower bound on the function. The intersection you have is the best option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

2 participants