I have been trying to google how to solve this problem but I'm having a hard time even coming up with what to search for, so any help in editing this question or linking me to duplicates would be very helpful.
The Use Case
I have a function that as a first argument takes a Record of "column names" as the keys and interface fields as the values. For example, a mapping of,
{
"user_id": "userID",
"email__": "email",
}
and an interface of,
interface ExpectedShape {
userID: number;
email: string;
}
Casting
For reasons beyond my control, the columns where my data is coming above are named user_id
and email__
, and will always be returned as strings. So I need to define how to cast or clean up incoming data when creating JS objects matching the ExpectedShape
interface.
So in order to allow this, I have a configuration variable in my method that will take the same keys as the original mapping but have methods that will cast things accordingly. For example,
{
"user_id": Number.parseInt,
"email__": sanitizeEmail,
}
So when user_id
comes in from the data source, it will call Number.parseInt
so that when it the ExpectedShape
object is built, it'll be a proper number.
What I want to do
Via TypeScript, I want to enforce that the keys of my "mapping" and my "casting operations" be the same.
Here is some broken code that does not work but shows what I'd envision it to look like.
interface ExpectedShape {
userID: number;
email: string;
}
interface FunctionOptions<K extends keyof any, S> {
casting: Record<K, (value: string) => S[keyof S]>;
}
function myFunction<T extends {}>(
values: Record<string, keyof T>,
config: FunctionOptions<keyof values, T>, // <-- What can I put here?
): Partial<T> {
return {};
}
function sanitizeEmail(_: string): string { return ""; }
const result = myFunction<ExpectedShape>(
{
"user_id": "userID",
"email__": "email",
},
{
// I want to restrict via TypeScript that the keys of `casting` must be
// the same as the keys of the `values` argument. See how it's missing
// an underscore?
casting: {
userid: Number.parseInt,
}
},
);
What I have tried...
I have tried a lot. The closest I've gotten it to work and compile successfully is this,
function myFunction<
T extends {},
M extends Record<string, keyof T> = Record<string, keyof T>,
P extends keyof M = keyof M,
>(
values: M,
config: FunctionOptions<P, T>,
): Partial<T> {
return {};
}
However. It does not enforce keys correctly and allows me to use whatever keys I want.
values
supposed to be a mapping of keys to keys? If so, why are you passing inNumber.parseInt
andsanitizeEmail
? How couldmyFunction
return aPartial<T>
when you don't even pass in a value from the original API?). My answer will just involve a general way of doing this at runtime and in the type system, and hopefully you can adapt it to whatever your specific use case is.