I have a typescript function that takes a generic type and a key for that generic type. I constrain that key so that the function will only accept keys where the values will be of a certain type. When accessing the generic object using the constrained key I don't get the expected type in return.
How do you constrain a key of a generic object to a specific value type and access that value in a generic function?
For example:
function onlyTakesADateKey<T, K extends keyof T>(item: T, key: T[K] extends Date ? K : never): void {
//I've constrained `key` to ensure that item[key] is a Date but this doesn't get typed as a Date
const shouldBeADateButIsNot = item[key]
//Property 'getTime' does not exist on type 'T[T[K] extends Date ? K : never]'.ts(2339)
shouldBeADateButIsNot.getTime()
}
const foo = { key1: "asdf", key2: new Date() }
//Argument of type 'string' is not assignable to parameter of type 'never'.ts(2345)
const bar = onlyTakesADateKey(foo, "key1")
//It properly constrains the key, but per above can't access the date value in the function
const baz = onlyTakesADateKey(foo, "key2")
Why isn't shouldBeADateButIsNot a Date? The key is properly constrained. I cannot pass arguments to the function that result it in not being a Date.