I am dealing with the following function in my codebase
export async function batchEntitiesBy<Entity, T extends keyof Entity>(
entityClass: EntityTarget<Entity>
by: T,
variables: readonly Entity[T][]
) {
by: T,
variables: readonly Entity[T][]
) {
// retrieve entities from the database without grouping and in random order
const entities = await db.find(entityClass, { [by]: In(variables as Entity[T][]) })
// group the entities and order the groups based on variables order
type EntityMap = { [key in Entity[T]]: Entity[]}
const entityMap = {} as EM;
entities.forEach((e) => {
if (!entityMap[e[by]]) {
entityMap[e[by]] = []
}
entityMap[e[by]].push(e)
})
return variables.map((v) => entityMap[v]);
}
I anticipate that Entity[T]
will provide me with the type of the class member specified in by
, making entityMap
a mapping from type(by) to type(Entity)
Why am I encountering this error??
Type 'Entity[T]' is not assignable to type 'string | number | symbol'.
Type 'Entity[keyof Entity]' is not assignable to type 'string | number | symbol'.
Type 'Entity[string] | Entity[number] | Entity[symbol]' is not assignable to type 'string | number | symbol'.
Type 'Entity[string]' is not assignable to type 'string | number | symbol'.
Edit:
If we take an example entity
class ExampleEntity {
a: string,
b: number
}
My expectations are:
by
should be eithera
orb
- If
by
isa
, then I would expectEntity[T]
to bestring
referring to TypeScript documentation https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types
Here demonstrating the same issue in playground
Edit2:
Below are some sample entities I intend to utilize with this function:
class User {
id: string
name: string
address: Address
addressId: number
}
class Address {
id: number
street: string
num: number
}
example usage:
const adrIds = [1,5,2,9,4]
const users = batchEntitiesBy<User, addressId>(Users, "addressId", adrIds)