microsoft / microsoft/TypeScript

Support conditional types for Generator T / TNext / TReturn

Open
#57,671 3 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
1d 19h
Merged PRs (30d)
117

Description

🔍 Search Terms

"Generator", "Async Generator", "conditional types", "const" "inference"

✅ Viability Checklist
⭐ Suggestion

If a generator function is specifically typed to have a conditional relationship between T and TNext then type inference should allow for a type narrowed result according to that conditional type.

📃 Motivating Example

Typescript would be able to support complex type state management (ala redux saga), coroutines (e.g. co) and the interpreter pattern / free monad/applicative.

In the past this was not possible, but given typescript now has as const, infer and conditional types, we should be able to support typed yield result inference in key circumstances.

Something like this would be possible:

type Yielded<T> 
  T extends Promise<infer U>
   ? U // awaited
   : T  // return the original yielded value
   
function co<T>( fn: () => Generator<T, T, Yielded<T>> ) : Promise<T> {...}
💻 Use Cases
  1. What do you want to use this for?

Complex state management and side effects.

  1. What shortcomings exist with current approaches?

For generator functions yielded values are always typed as any. For async generators yielded values are a union of all possible results.

  1. What workarounds are you using in the meantime?

Manually casting

doSomething(function * f(){
    let value = (yield someStream) as UnwrapStream<typeof someStream>
    let another = (yield somePromise) as UnwrapPromise<typeof somePromise>
})

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 with the motivating generator example and compare the requested conditional relationship between T, TNext, and TReturn with the stated current behavior for generators and async generators. Done means conditional inference supports the described typed yield results without changing emitted JavaScript, with coverage for the motivating cases.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.