I am currently working on defining a generic TypeScript function that can accept a Record<number, boolean>
and return the same value. The challenge I am facing is ensuring that the input type remains generic and is reflected accurately in the output.
I have noticed that when I call the function and pass something other than a number (specifically a string) as the record key, I do not receive an error:
const func = <T extends Record<number, boolean>>(input: T): T => input;
const x = func({
1: true,
test: false // <-- no error shown
})
If I inline the type Record<number, boolean>
, it works but then I lose the ability to use it in my return type:
const func2 = (input: Record<number, boolean>): Record<number, boolean> => input;
const y = func2({
1: true,
test: false // <-- error detected
});
// ^? y: Record<number, boolean> - and not { 1: true }
I am looking for a way to constrain my types so that errors are caught for the input while also maintaining the integrity of the output type.
Disclaimer: This example has been simplified. In actual code, there are more generic parameters at play and T
is utilized in various instances, including in a more complex return type based on T.