Trying to solve the puzzle of accurately coding a show
function that requires an object T
and a key K
where T[K]
definitely has a method named toString()
.
Here's my approach using mapped types
type ToStringablePropertyKeys<T> = keyof {
[K in keyof T]: { toString(): string }
}
function show<T, K extends ToStringablePropertyKeys<T>>(t: T, k: K): string {
return t[k].toString()
}
However, the compiler is giving me an error -
Property 'toString' does not exist on type 'T[K]'.
What could I be overlooking here? How can I assure tsc
that toString
certainly exists due to definition of K
?