microsoft / microsoft/TypeScript

Inferred type parameter does not satisfy constraint

Open
#45,286 0 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Type Inference
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

generic constraint, inference, invalid, specified, manually, explicitly, invalid

🕗 Version & Regression Information
  • This changed between versions 3.3 and 3.5
⏯ Playground Link

Playground link with relevant code

💻 Code
declare function f<T, U extends T>(cb: (u: U) => T): U

const v = f(u => "x");
// const v: unknown <-- wait, what?
// function f<string, unknown>(cb: (u: unknown) => string): unknown

f<string, unknown>(u => "x"); // error, of course
// -----> ~~~~~~~
// Type 'unknown' does not satisfy the constraint 'string'.
🙁 Actual behavior

In TS3.5+, the type parameter T is inferred to be string, and U is inferred to be unknown in the first call to f(). But then U extends T is not met; you couldn't even manually specify T and U like this when calling f(), as shown in the second call to f().

(In TS3.3, T and U are both inferred as {}.)

🙂 Expected behavior

Either I'd expect both T and U to be string, or I'd expect an error where the compiler says it cannot find a suitable candidate for U. Presumably the compiler has not inferred T before it needs to infer U, and so it constrains U to T's constraint which is implicitly unknown, and then falls back to that. But it never circles back to make sure that such a fallback actually works for U extends T.


I came upon this while looking for an answer to this SO question. This behavior is weird, right? I haven't found an existing issue for it.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the linked TypeScript Playground example and compare the reported behavior with TypeScript 3.3 and 3.5+. Start by tracing generic type inference and constraint checking for the shown function calls. Done means the compiler handles the inferred U extends T constraint consistently and has regression coverage for the selected expected behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.