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

Cannot index into generic type if unions involved #23618

Closed
osdiab opened this issue Apr 22, 2018 · 0 comments
Closed

Cannot index into generic type if unions involved #23618

osdiab opened this issue Apr 22, 2018 · 0 comments
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@osdiab
Copy link

osdiab commented Apr 22, 2018

TypeScript Version: 2.8.1

Search Terms: typescript intersection union "cannot be used to index"

Code

// This works:
type DBBoolTable<K extends string> = { [k in K]: 0 | 1 } 
enum Flag {
  FLAG_1 = "flag_1",
  FLAG_2 = "flag_2"
}

type SimpleDBRecord<Flag extends string> = { staticField: number } & DBBoolTable<Flag>
function getFlagsFromSimpleRecord<Flag extends string>(record: SimpleDBRecord<Flag>, flags: Flag[]) {
  // stub
  return record[flags[0]]
}

// This fails:

type DynamicDBRecord<Flag extends string> = ({ dynamicField: number } | { dynamicField: string }) & DBBoolTable<Flag>
function getFlagsFromDynamicRecord<Flag extends string>(record: DynamicDBRecord<Flag>, flags: Flag[]) {
  // stub
  return record[flags[0]] // Error: Type 'Flag' cannot be used to index type 'DynamicDBRecord<Flag>'
}

I know in this example I can just say dynamicField: number | string, but in my actual code there's a more complex type than just one field like that (and contains outside constraints like DB schema).

Expected behavior:
I should be able to index into the db record in the second example even with that dynamic field, because the DBRecord type says it should have all the flags in it.

Actual behavior:
It is unhappy with indexing into the type with a union in it, with the error mentioned above.

Playground Link

Related Issues:
Not sure

@mhegazy mhegazy added the Bug A bug in TypeScript label Apr 23, 2018
@mhegazy mhegazy added this to the TypeScript 2.9 milestone Apr 23, 2018
@ahejlsberg ahejlsberg assigned ahejlsberg and unassigned sandersn Apr 23, 2018
@ahejlsberg ahejlsberg added the Fixed A PR has been merged for this issue label Apr 23, 2018
@microsoft microsoft locked and limited conversation to collaborators Jul 31, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

4 participants