microsoft / microsoft/TypeScript

Probable bug: Functional properties don't get inferred with circular type parameter constraints like `T extends M<T>`

Open
#40,439 14 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs Investigation
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version:
4.0.2

Search Terms:
Circular type parameter constraint, functional property inference, function parameter inference, function argument inference

Code:

declare const m: <T extends M<T>>(m: T) => T
type M<Self, K = Exclude<keyof Self, "k" | "t">> =
  { a?: number
  , b?: number
  , c?: number
  , d?: number
  , k?: K
  , t?: (k: K) => void
  }

// :)
// Case 1
m({
  a: 1,
  b: 2,
  k: "a"
})

// :)
// Case 2
m({
  a: 1,
  b: "x", // expected error
  k: "c" // expected error
})

// :(
// Case 3
m({ // type parameter becomes `unknown` (probably because t's first parameter is `any` initially kinda?)
  a: 1,
  b: 2,
  k: "a", 
  t: k => {} // k is inferred as `never` (instead of `"a" | "b"`)
})

// :|
// Case 4
m({
  a: 1,
  b: 2,
  k: "a", 
  t: (k: "a" | "b") => {} // have to explicitly type `k` which could have been inferred :(
})

Expected behavior:
The parameter k of t should be inferred as "a" | "b". As property k already gets inferred in Case 1 & 2, so why not the k parameter of t

Actual behavior:
The parameter of t is inferred as never and T in inferred as unknown. I assume first T gets resolved to unknown as t is initially inferred as (k: any) => void which does not satisfy the constraint of m.

Playground

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

Start by reproducing the circular-constraint example in the linked TypeScript Playground and compare the inferred types in Cases 3 and 4. Trace the compiler's type-parameter and function-parameter inference for T extends M; done means the parameter k is inferred as "a" | "b" and T is no longer unknown.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.