I'm trying to figure out how to correctly type a show function that would take an object T and a key K for which T[K] can be guaranteed to have a toString() method implemented.
Here is my attempt 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()
}
But the compiler says Property 'toString' does not exist on type 'T[K]'.
What am I missing here? How do I convince tsc that toString is in fact there by definition of K?
An alternative approach:
function show<K extends string, T extends {[key in K]:{toString(): string}}>
(t: T, k: K ): string {
return t[k].toString()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With