I'm encountering some challenges when working with Generics in TypeScript.
My goal is to create an object based on another object type using Generics. I initially referenced this TypeScript documentation
This is the code snippet I have come up with so far:
type ClickableItem<T extends Record<string, any>, K extends keyof T> = {
label: string;
key: K;
render?: (value: T[K]) => string;
// The value (argument) type here should reflect the type from the selected key
};
The current issue
When attempting to use the ClickableItem type in an object, the argument type of render
becomes a union of all possible type values. For example:
type Example = {
a: string,
b: number
}
const item = {
label: 'x',
key: 'a',
render: (value) => value //ERROR HERE
} satisfies ClickableItem<Example, keyof Example>
The render method is being inferred incorrectly as type string | number
, even though the key a
is explicitly set to type string
In the previous example, the type of the render method should be (value: string)=> string
instead of the inferred type
(value: number | string)=> string
.
Here's the TypeScript Playground link which showcases both the original example from TypeScript's documentation and my aforementioned test implementation