microsoft / microsoft/TypeScript
Optional Generic Type Inference
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
#13487 added default generic types, but it's still not possible to infer a generic type:
type Return<T extends () => S, S = any> = S
Here S takes its default type any, but T could permit inference of a subset type of any for S:
const Hello = () => 'World'
type HelloReturn = Return<typeof Hello> // any
Here HelloReturn still has any type, and TypeScript could infer S as the literal type 'World', which is a subset of any.
Use Case
Here's an example of a fully declarative workaround for #6606, using generic type inference:
type Return<T extends () => S, S = any> = S
const Hello = () => 'World'
type HelloReturn = Return<typeof Hello> // 'World'
Default Type
If return of T is not a subset of S, it should throw an error:
type ReturnString<T extends () => S, S = string> = S
const Hello = () => 'World'
type HelloReturn = ReturnString<typeof Hello> // 'World'
const calculateMeaningOfLife = () => 42
type MeaningOfLife = ReturnString<typeof calculateMeaningOfLife> // ERROR: T should return a subset of String
Multiple Possible Type Inferences
The current implementation always returns the superset (which is just the default generic type), solving this issue would require to return the subset (the most precise type of all the inferred possibilities).
If a type has multiple possible type inferences, TypeScript should check that all these types are not disjoint, and that they all are subsets of the Default Generic Type.
The inferred type is the most precise subset.
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
The issue names no files, tests, or entry points. Start by reproducing the generic-inference examples in a TypeScript type-checking environment and tracing the existing behavior for default generic types; done means the inferred type is the most precise valid subset and incompatible returns are rejected.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100