8000 Type parameter cannot be inferred from another in simple case · Issue #35331 · microsoft/TypeScript · GitHub
[go: up one dir, main page]

Skip to content
Type parameter cannot be inferred from another in simple case #35331
Closed
@dgreensp

Description

@dgreensp

TypeScript Version: 3.7.2 and 3.8.0-dev.20191123

Search Terms: Inference, generic function, unknown, argument not assignable, type parameter

Code

type Foo<T> = (t: T) => T
const increment: Foo<number> = x => x + 1

declare function acceptFoo<T>(foo: Foo<T>): void
acceptFoo(increment) // Works

declare function acceptFoo2<T, F extends Foo<T>>(foo: F): void
acceptFoo2(increment) // Error, argument not assignable to Foo<unknown>

// Work-around: explicitly intersect F with its bound
declare function acceptFoo3<T, F extends Foo<T>>(foo: Foo<T> & F): void
acceptFoo3(increment) // Works

Expected behavior:

Inference results in T being number, not unknown. No type error at acceptFoo2 call site.

Actual behavior:

T is unknown, causing a type error.

Note that if Foo were covariant in T, not invariant (as in this case) or contravariant, the above code would type-check, but the poor type for T could still be impactful, for example if T were part of the return type of acceptFoo. It's fortunate that the above work-around, using an intersection, is available. Without that, you'd have to specify all type parameters at the call site, because TypeScript doesn't yet support specifying some type parameters and inferring the rest. I am creating some APIs where it would be very inconvenient for the user to explicitly write out all the type parameters that would be inferred.

For some reason I thought TypeScript's inference was smart enough to go through one type parameter to another, but I tried this code on versions back to 2.8.1 and the result is the same.

Playground Link: http://www.typescriptlang.org/play/?ts=3.8.0-dev.20191123&ssl=1&ssc=1&pln=12&pc=31#code/C4TwDgpgBAYg9nAPAFQHxQLxQBTAFxTICUm6yAsAFADGcAdgM7BQCWd1AThALYR36wEiOgFduAIwgd0WAB6ko8gNRQAjFSoATCNQA2AQy5QAZiPbAW9KPurUIYYPCRpsxhAScpURAgDc4LJpUNnYOTthsnDx8wCQA9HFQAOpwHADWDBqU2nqG0KbmlnTWtvaOCABMKAA0sFAQssB8mgyCzqioru6wPlD+gcGlYZUR7Fy8-PGJAKIcHKm1hgDmYjFQdHDM+gwMLEt0+uK60MBwbYhmaRsA7nSoWQnJqWkAtIZwZpoEDWC6LNQsYC6ECsfhSBg6ZgwKDXQEAC1YwFa4g+dCC2R0BiMBWoFisITKTgAzDU6g0mmjWp40J03HAPEI0FAAGQ9PwBdEE4ZwImjKITWJQR4pdIMIA

Related Issues:

Possibly related to #35288, which is about inference not taking advantage of the fact that a class Foo extends interface IFoo.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0