microsoft / microsoft/TypeScript

Type inference inconsistency with generic constraints

Open
#43,804 1 comment 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

Bug Report

🔎 Search Terms
  • type inference const string
  • type inference generic constraints
🕗 Version & Regression Information

Tested on

  • 3.9.7
  • 4.2.3
  • 4.3.0-beta
⏯ Playground Link

Playground link

💻 Code

Following Generic Constraints

type Concatable<T> = {
	concat: (...xss: T[]) => T
};

export const concat = <T extends Concatable<T>>
	(xs: T, ...xss: T[] ): T => xs.concat( ...xss );

export const test_1 = concat([1, 2], [3, 4]);         // OK
export const test_2 = concat("foo" as string, "bar"); // OK
export const test_3 = concat<string>("foo", "bar");   // OK

// Expected: 'test_4: string'
// Got:      'test_4: Concatable<"foo" | "bar">'
export const test_4 = concat("foo", "bar");
// Error:                    ^^^^^
// Argument of type 'string' is not assignable to
// parameter of type 'Concatable<"foo" | "bar">'
🙁 Actual behavior

test_4: Concatable<"foo" | "bar">

TS leaks the constraint for type T into type T
TS provides no good way to make Rust-like trait

🙂 Expected behavior

T, test_4, "foo" and "bar" all infer type string

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 generic-constraint example in the linked TypeScript Playground across the listed versions and inspect the inferred type of test_4. The fix is complete when concat("foo", "bar") infers string without an error, matching the expected behavior while preserving the other examples.

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
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.