Welcome to the coding playground:
Let's talk about a scenario where a function is expected to return some value based on an input argument. The challenge arises when there are keys with the same name but different types resulting in a union of values:
const qu = {
q2: {
obj1: 'test',
obj2: 'test2'
},
q3: {
obj1: 2,
obj2: 234
}}
Is there any method to automatically infer the type, instead of manually setting it or using conditionals which might not work as intended in TypeScript?
Below is a complete example of the code snippet above for reference:
type q = {
[key: string]: {
obj1: any,
obj2: any
}}
const qu = {
q2: {
obj1: 'test',
obj2: 'test2'
},
q3: {
obj1: 2,
obj2: 234
}}
const queryFn = <T extends q>(obj: T) => <K extends keyof T>(q: K): T[K]['obj1'] => {
const {obj1, obj2} = obj[q]
return obj1
}
const qur = queryFn(qu)
const someotherfn = (arg: Parameters<typeof qur>[0]) => {
let res: ReturnType<typeof qur<typeof arg>>
res = qur(arg)
return res
}
const res = someotherfn('q3') // Expected output should infer correct type, not union