Skip to content

Cannot index into generic type if unions involved #23618

Closed
@osdiab

Description

@osdiab

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

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions