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 error when using type parameters as constraints #8411

Closed
spikefoo opened this issue May 1, 2016 · 2 comments
Closed

Type inference error when using type parameters as constraints #8411

spikefoo opened this issue May 1, 2016 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@spikefoo
Copy link

spikefoo commented May 1, 2016

When compiling the following code: (the function call takes a 0-argument function and returns its result)

type NoArgsFn<T> = () => T;

function call<T, Fn extends NoArgsFn<T>>(fn: Fn): T {
  return fn();
}

let result: number = call(() => 1);

I get the following incorrect error: (on the last line)

try.ts(7,5): error TS2322: Type '{}' is not assignable to type 'number'.

The following workaround, adding an unused dummy argument of type T to the function, avoids this error:

type NoArgsFn<T> = () => T;

function call<T, Fn extends NoArgsFn<T>>(fn: Fn, dummy: T): T {
  return fn();
}

let result: number = call(() => 1, -1);
@mhegazy
Copy link
Contributor

mhegazy commented May 1, 2016

duplicate of #7234

@mhegazy mhegazy closed this as completed May 1, 2016
@mhegazy mhegazy added the Duplicate An existing issue was already created label May 1, 2016
@malibuzios
Copy link

Hi, I believe the problem seems to be that type argument inference isn't 'smart' enough here to infer R from the function type () => R, which involves a reference to a generic parameter.

(I simplified the example a bit)

function call<R, F extends () => R>(func: F): R {
  return func();
}

let result: number = call(() => 1);

Despite the fact that the constraint doesn't error, It doesn't actually know how to infer R so it defaults to {}.

Another workaround is of course to use the signature () => R or its type alias directly as the type instead of as a constraint:

function call<R>(func: () => R): R {
  return func();
}

let result: number = call(() => 1);

But I'm not sure if that was the intention here.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants