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

Suggestion: Allow union in index signature if all members of union are string or number #21570

Closed
drew-gross opened this issue Feb 2, 2018 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@drew-gross
Copy link

drew-gross commented Feb 2, 2018

This code is currently not allowed:

interface I {
    [index: 'a' | 'b']: number;
}

Probably because it's pretty much equivalent to this code:

interface I {
    a: number;
    b: number;
}

However, if the union is actually a type argument, it's not equivalent:

interface I<T> {
    [index: T]: number;
}

I think this would be useful. Potentially with some extra syntax to help clarify the api, something like:

interface I<T: union> {
    [index: T]: number;
}

For my specific use case, I am implementing a parsing library, and wish to have an API like this:

export type Parser<AstNodeName> = /* Some stuff involving AstNodeName */;

export interface Grammar<AstNodeName> {
    [index: AstNodeName]: Parser<AstNodeName>;
}

Which will be used like this:

type AstNodes = 'plus' | 'minus';
const myGrammar: Grammar<AstNodes> = {
    'plus': (n: AstNodes) => doSomeStuff(n),
    'minus': (n: AstNodes) => doDifferentStuff(n),
}
@drew-gross drew-gross reopened this Feb 2, 2018
@weswigham
Copy link
Member

This is probably a duplicate of #2049, if I understand your request correctly.

@mhegazy mhegazy added the Duplicate An existing issue was already created label Feb 2, 2018
@drew-gross
Copy link
Author

Yep, I think it is.

@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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants