I'm having trouble understanding the code snippet below:
interface Example {
first?: number,
second?: {
num: number
}
}
const example: Example = {
first: 1,
second: { num: 2 }
}
function retrieveValue<Object, Key extends keyof Object>(obj: Object, key: Key): Object[Key] {
return obj[key]
}
let a = retrieveValue(example, 'first') // Successfully compiles, type of a is number | undefined
let b = retrieveValue(example.second, 'num') // Argument of type '"num"' is not assignable to parameter of type 'never'.
In this scenario, a
has a type of number | undefined
, which is as expected. However, b
is assigned the type never
. Why does this happen? I would anticipate { num: number } | undefined
instead.
What am I overlooking, and how can I modify the code for successful compilation?