Classes Defined:
abstract class ModelBase {
id: string;
}
class Person extends ModelBase {
favoriteDog: Dog | undefined;
favoriteDogId: string | undefined;
dogs: Dog[]
}
class Dog extends ModelBase {
id: string;
ownerId: string;
name: string;
}
In the scenario of having arrays of Persons and Dogs, I wish to map them using a method like:
const persons = [{ id: 'A', favoriteDog: undefined, favoriteDogId: 'B'}];
const dogs = [{ id: 'B', name: 'Sparky'}];
mapSingle(persons, "favoriteDog", "favoriteDogId", dogs);
console.log(persons[0].favoriteDog?.name); // logs: Sparky
The code snippet for mapping:
static mapSingle<TEntity extends ModelBase , TDestProperty extends keyof TEntity, TDestPropertyType extends (TEntity[TDestProperty] | undefined)>(
destinations: TEntity[],
destinationProperty: keyof TEntity,
identityProperty: keyof TEntity,
sources: TDestPropertyType[]) {
destinations.forEach(dest => {
const source = sources.find(x => x["id"] == dest[identityProperty]);
dest[destinationProperty] = source; // <--- Error Line
});
}
Error encountered:
TS2322: Type 'TDestPropertyType | undefined' is not assignable to type 'TEntity[keyof TEntity]'
Type 'undefined' is not assignable to type 'TEntity[keyof TEntity]'.
The error arises due to defining a property as nullable in the method.
Subsequently, a similar method could be created with analogous tactics;
mapMany(persons, 'Dogs', 'OwnerId', dogs);
Additional Resources:
In TypeScript, how to get the keys of an object type whose values are of a given type?