In the setting I'm dealing with, specific objects with an id
attribute expire every "tick" and require retrieval using getObjectById
. I am interested in creating a setter function to update a property of an object by mapping
thing.property => getObjectById(thing.property.id)
. This function should accept a thing T
and a key K
, where T[K]
can either be an object with an id (HasID
) or an array of such objects (HasID[]
).
I believe I am close to a solution, but it requires some adjustments. The current implementation is as follows (a static method in a class named $
):
static refresh<T extends {[K in keyof T]: HasID}, K extends keyof T>(thing: T, key: K): void;
static refresh<T extends {[K in keyof T]: HasID[]}, K extends keyof T>(thing: T, key: K): void;
static refresh<T extends {[K in keyof T]: HasID | HasID[]}, K extends keyof T>(thing: T, key: K): void {
if (_.isArray(thing[key])) {
thing[key] = _.map(thing[key] as HasID[], s => getObjectById(s.id)) as HasID[];
} else {
thing[key] = getObjectById(thing[key].id) as HasID;
}
}
For instance, the desired outcome for
foo: {bar: HasID, baz: HasID[], biz: string[]}
would be:
$.refresh(foo, 'bar') // foo.bar = getObjectById(foo.bar.id)
$.refresh(foo, 'baz') // foo.baz = _.map(foo.baz, x=>getObjectById(x.id))
$.refresh(foo, 'biz') // error: foo.biz is not HasID or HasID[]
$.refresh(foo, 'boo') // error: 'boo' is not a key of foo
Can someone offer guidance on how to correctly define the type of T[K]
?