Skip to content

Indexer with type parameter #4896

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

Closed
jbondc opened this issue Sep 21, 2015 · 4 comments
Closed

Indexer with type parameter #4896

jbondc opened this issue Sep 21, 2015 · 4 comments
Labels
Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. Suggestion An idea for TypeScript

Comments

@jbondc
Copy link
Contributor

jbondc commented Sep 21, 2015

type MapThing<T> = {
    [x: string]: T; // Property 'length' of type 'number' is not assignable to string index type 'T'.
    length: number;
}
let a: MapThing<number>;
let b: MapThing<string>;

interface MapThingi<T> {
    [x: string]: T; // Property 'length' of type 'number' is not assignable to string index type 'T'.
    length: number;
}
let c: MapThingi<number>;
let d: MapThingi<string>;

A type parameter on an indexer is checked eagerly, should happen on instantiation.

@DanielRosenwasser
Copy link
Member

Perhaps, but alternatively, you could type MapThing as:

interface MapThing<T> {
    [x: string]: T | number;
    length: number;
}

or just omit the type parameter if you know you're only going to be using number for T:

interface MapThing {
    [x: string]: number;
    length: number;
}

@DanielRosenwasser DanielRosenwasser added the Suggestion An idea for TypeScript label Sep 21, 2015
@weswigham
Copy link
Member

I would like to think that this:

interface Map<T> {
    [x: string]: T;
}

type MapThing<T> = Map<T> & { length: number; };

Would be the best way to represent that at present. There's no compromises in genericness, signatures, or completion assistance when represented this way.

@jbondc
Copy link
Contributor Author

jbondc commented Sep 21, 2015

👍

You both got me thinking about:

type MapThingConflict<T> = Map<T> & { length: number; } & { length: string; } & { length: boolean; } ; 

Should be an error or a combined/merged type as something like this?

interface MapThingConflict<T> {
    [x: string]: T;
    length: boolean
}

@mhegazy mhegazy added the Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. label Dec 10, 2015
@RyanCavanaugh
Copy link
Member

I think the behavior here is effectively calcified

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

5 participants