Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tagged union inference in mapped type with generic key #20775

Closed
felipeochoa opened this issue Dec 19, 2017 · 3 comments
Closed

Tagged union inference in mapped type with generic key #20775

felipeochoa opened this issue Dec 19, 2017 · 3 comments
Labels
Needs More Info The issue still hasn't been fully clarified

Comments

@felipeochoa
Copy link

TypeScript Version: 2.6.2; Playground

Code

interface T {
    a: { k: 'n', v: number },
    b: { k: 's', v: string },
}

function f<K extends 'a'|'b'>(t: T[K]) {
    if (t.k === 'n') {
        return t.v * 5;
    } else {
        return t.v.charCodeAt(0);
    }
}

Expected behavior: t should be narrowed so that the two clauses are accepted by the compiler

Actual behavior: t.v is typed as string | number in both branches.

This is similar to #17930, but this issue adds the generic K to the mix.

@DanielRosenwasser
Copy link
Member

DanielRosenwasser commented Dec 19, 2017

As solved in #17930, I don't think you need K in this example.

interface T {
    a: { k: 'n', v: number },
    b: { k: 's', v: string },
}

function f(t: T[keyof T]) {
    if (t.k === 'n') {
        return t.v * 5;
    }
    else {
        return t.v.charCodeAt(0);
    }
}

Do you have specific pattern you're trying to model?

@DanielRosenwasser DanielRosenwasser added the Needs More Info The issue still hasn't been fully clarified label Dec 19, 2017
@felipeochoa
Copy link
Author

I realize K is superfluous here, but this was an illustrative example. In the real case, I'm using mapped types to narrow multiple values simultaneously. The real function is more like:

function f<K extends 'a'|'b'>(k: K, t1: T1[K], t2: T2[K])

which I type that way to ensure T1 and T2 are compatible (i.e. correspond to the same union case).

@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Needs More Info The issue still hasn't been fully clarified
Projects
None yet
Development

No branches or pull requests

3 participants