Closed
Description
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.
Related Issues:
Not sure