microsoft / microsoft/TypeScript

Allow narrowing generic type to single element of union type

Open
#17,713 6 comments 5 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

It is a fairly common pattern to create a set of generic components, and then to use the generic component type within the system. Currently, typescript has an issue handling cases where some values of a generic component depend on others.

TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)
2.4
Code

let index = {
    a: {
        arg: 'a',
        fn: (a: string) => {a.toUpperCase()}
    },
    b: {
        arg: 1,
        fn: (b: number) => {b + 1}
    }
}

let runFn= <K extends keyof (typeof index)>(key: K) => {
    let i = index[key]
    let arg = i.arg
    let fn = i.fn
    fn(arg) // Error: compiler doesn't understand that fn and arg will match
}

Expected behavior:
No error, since we know that arg and fn are pulled off of the same map entry.

Actual behavior:
Error: cannot invoke expression whose type lacks a call signature

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 provided TypeScript 2.4 example and confirm the error when invoking fn(arg). Then trace the type-checking path for indexed access through a generic key and dependent union members; done means the example compiles without weakening type safety.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.