I have the bellow function
export async function batchEntitiesBy<Entity, T extends keyof Entity>(
entityClass: EntityTarget<Entity>
by: T,
variables: readonly Entity[T][]
) {
by: T,
variables: readonly Entity[T][]
) {
// get entities from database ungrouped and in random order
const entities = await db.find(entityClass, { [by]: In(variables as Entity[T][]) })
// group the entities and order the groups by 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 would expect Entity[T] to give me the type of the class member specified in by and therefore entityMap to be a mapping from type(by) to type(Entity)
why am I getting 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 I have an example entity
class ExampleEntity {
a: string,
b: number
}
I would expect
byto be eitheraorb- If
byisaI would expectEntity[T]to bestring
based on the typescript documentation https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types
Here illustrating the same problem in playgroud
Edit2:
Some example entities I would like to use 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)
Entity[T]cannot be used as a key. Did you mean to useT?Entity[T]always maps to a valid key.