I am currently facing an issue where I need the get function to limit the p parameter to the combination of all the types of key2 in the array. Additionally, key3 should be a keyof TFooKey.
type Foo<TFoo, TFooKey extends Record<string, any>> = {
key1: TFooKey
key2: TFoo
key3: keyof TFooKey
}
// The goal is to have p as a union of all the types for key2 in the tuple
function get<TFoo, TFooKey extends Record<string, any>>(t: readonly Foo<TFoo, TFooKey>[], p: TFoo) {
return t
}
// The issue arises when TFoo is only inferred from the first element
get(
[
{
key1: {
key: ""
},
key2: "",
key3: ""
},
{
key1: {
key: ""
},
key2: 0,
key3: ""
}
] as const,
""
)
function get2<T extends readonly Foo<string | number, Record<string, any>>[]>(t: T, p: T[number]["key2"]) {
return t
}
// While this solution works, it compromises on ensuring that key3 is a keyof TFooKey
get2(
[
{
key1: {
key: ""
},
key2: "",
key3: "key"
},
{
key1: {
key: ""
},
key2: 0,
key3: "anyKey"
}
] as const,
0
)
Above are the approaches I have tried and explained why they fall short. Is achieving this scenario even feasible?