microsoft / microsoft/TypeScript

Change infer keyword behaviour to use it for type caching

Open
#39,958 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Search Terms

infer type cache

Suggestion

I saw one proposal somewhere, but I can't find it now. There people asked to add possibility of using type level variables inside type level computations. I realized now that simple constructions with infer keyword may be used for this after a small behaviour change:

type VERY_HEAVY_COMPUTATION<T> = T extends number ? 42 : []

type MakePair<P extends number, R extends number> = [P, R]

type Result = VERY_HEAVY_COMPUTATION<0> extends infer Cached
  // Error: Type 'Cached' does not satisfy the constraint 'number'.ts(2344)
  ? MakePair<Cached, Cached> : never

Currently in this case VERY_HEAVY_COMPUTATION<0> doesn't share its value with Cached automatically, so we need compute the value twice.

type Result = VERY_HEAVY_COMPUTATION<0> extends infer Cached
  ? Cached extends VERY_HEAVY_COMPUTATION<0>
    ? MakePair<Cached, Cached> : never
  : never

I suggest, in the case of such constuctions A extends infer Cache ? ... : ..., automatically share the type of A with Cache

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 issue's VERY_HEAVY_COMPUTATION, MakePair, and Result examples and compare the current behavior of A extends infer Cache ? ... : .... Determine how type caching should work without requiring the repeated conditional check; done means the proposed Result form type-checks while preserving the intended inferred type.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.