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

Can't access indexed type using keyof when using number as an indexer #14068

Closed
adharris opened this issue Feb 14, 2017 · 1 comment
Closed
Labels
Duplicate An existing issue was already created

Comments

@adharris
Copy link

TypeScript Version: 2.1.6

I have a collection of entities mapped by numeric ID, and a function that plucks a single property out of the collection:

interface Foo { fooProp1: string, fooProp2: number[] }
interface Bar { barProp1: boolean, barProp: string }

interface Models {
    foos: {[id: number]: Foo}
    bars: {[id: number]: Bar}
}

function pluckProperty(models: Models, modelName: string, modelId: number, property: string) {
    ...
}

I'd like to use keyof to add strong typings to that function, but can't traverse the numeric indexer to get the indexed type. Something like this works if i index using strings instead:

function pluckProperty<K1 extends keyof Models,
                       K2 extends keyof Models[K1],
                       K3 extends keyof Models[K1][K2]>(
    models: Models, modelName: K1, modelId: K2, property: K3): Models[K1][K2][K3] {
 ...
}

This works, i think, because keyof {[key: string]: T} is string, but wont work when indexing by number because keyof {[key: number]: T} is never.

I've been able to work around this limitation by doing this:

type IdMapped<T> = {[P in keyof T]: {[id: number]: T[P]}}

interface ModelMap {
    foos: Foo;
    bars: Bar;
}   

type Models = IdMapped<ModelMap>;


function pluckProperty<K1 extends keyof Models, K2 extends keyof ModelMap[K1]>(
    models: Models, modelName: K1, modelId: number, property: K2): ModelMap[K1][K2] {
 ...
}

But that feels hackish, and if keyof is supported for string indexers then i feel it should probably work for the numeric case too.

@mhegazy
Copy link
Contributor

mhegazy commented Feb 14, 2017

Duplicate of #13715

@mhegazy mhegazy added the Duplicate An existing issue was already created label Feb 14, 2017
@mhegazy mhegazy closed this as completed Apr 21, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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

2 participants