Apologies if this question is repetitive, as I am new to TypeScript and struggling to identify related issues due to the complexity of some questions. The issue I'm facing involves TS coercing a type to never
, which is confusing me. Here's the scenario:
interface BigObject {
foo: {
a?: string
b?: string
}
bar: {
c?: string
d?: string
}
}
const instance: BigObject = {
foo: {
a: "a",
b: "b",
},
bar: {
c: "c",
d: "d",
}
}
function metafunction(bigObjProp: keyof BigObject) {
type LittleObject = BigObject[typeof bigObjProp]
return function (littleObjProp: keyof LittleObject) {
return function (bigObject: BigObject) {
const littleObject = bigObject[bigObjProp]
return littleObject ? littleObject[littleObjProp] : "fallback value"
}
}
}
const firstClosure = metafunction("foo")
const secondClosure = firstClosure("a")
const value = secondClosure(instance)
I expect the value of value
to be "a".
The confusion arises from littleObjProp
resolving to never
. My intuition was that since LittleObject
is derived from the argument passed into metafunction
, TypeScript would determine which "sub interface" to use for each invocation. However, it always defaults to thinking that keyof LittleObject
equals never
.
If anyone could help clarify why this is happening and provide guidance on achieving my goal, I would greatly appreciate it. Due to constraints with React libraries, I need to maintain the same structure of nested functions seen in the example. Please keep explanations simple, as I am still learning TypeScript. Thank you!