With the following classes:
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;
}
If have an array of Persons and an Array of Dogs, I'd like 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
I have the following code:
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:
TS2322: Type 'TDestPropertyType | undefined' is not assignable to type 'TEntity[keyof TEntity]'
Type 'undefined' is not assignable to type 'TEntity[keyof TEntity]'.
I get the error message, I'm having trouble with the language to specify that the property can be (maybe the compiler can even check that it should be) undefine-able.
Eventually I would create a similar method, using similar tactics;
mapMany(persons, 'Dogs', 'OwnerId', dogs);
Related Reading:
In TypeScript, how to get the keys of an object type whose values are of a given type?