My theory: Is it feasible to generate a guard from TypeDefs that will be present at runtime? I recall hearing that this is achievable with TS4+.
Essentially, two issues; one potentially resolvable:
If your API (which you can't control) provides noisy data and you need to filter them based on existing type definitions, what approach would you take?
At times, your type definitions may appear unconventional, making it challenging to filter by
lodash.keyBy
as theiteratee
could vary in shape depending on the given TypeDefs.
For instance:
You have an object type defined as follows:
type ObjectType = {
[key: string]: {
foo?: string | number;
};
};
The following data would pass based on the above ObjectType
:
const someOKCollection: Array<ObjectType> = [
{ june: { foo: 1 } },
{ earth: {} },
{ milky: { foo: "Hi" } }
];
Imagine this data is received from an API:
const collectionFromApi: Array<unknown> = [
{ car: { foo: 1 } },
{ soup: {} },
{ water: { foo: "Hi" } },
{ sun: { bar: "Hi" } }
];
In this scenario, the entry for sun
is unnecessary due to the ObjectType
(as it contains bar
). The challenge lies in transforming the data into:
const desiredResult = {
noMatter: { foo: 1 },
what: {},
Ever: { foo: "Hi" }
};
Main Question:
Ignoring the solvability of the first question, how should the iteratee
be automatically crafted from the TypeDefinition so that utilizing lodash.keyBy or other collection functions results in the desired outcome?
UPDATE: Explore a simplified CodeSandBox here: https://codesandbox.io/s/typescript-lodash-types-6844w0?file=/src/index.type.ts (please note: root key names may differ at runtime; only TypeDefs must be adhered to)