I have the following function:
const infer = (...params: string[]): Record<string, string> => {
const obj: Record<string, string> = {};
// Put all params as keys with a random value to obj
// [...]
return obj;
}
This function will take n strings and return an object containing exactly those strings as keys, with random values.
So infer("abc", "def")
might return {"abc": "1337", "def":"1338"}
.
Is there any way to infer the return type to get complete type-safety from this function? The code of the function guarantees that each key will be present in the returned object and that each value will be a string.
You could declare it like this:
const infer = <T extends string[]>(...params: T): Record<T[number], string> => {
const obj: Record<string, string> = {};
// Put all params as keys with a random value to obj
// [...]
return obj;
};
const t = infer("a", "b", "c") // const t: Record<"a" | "b" | "c", string>
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With