microsoft / microsoft/TypeScript
Type inference inconsistency with generic constraints
Open
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
💻 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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