Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript select string properties [duplicate]

Tags:

typescript

tsc

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?

like image 839
francoisr Avatar asked Jun 03 '26 09:06

francoisr


1 Answers

An alternative approach:

function show<K extends string, T extends {[key in K]:{toString(): string}}>
(t: T, k: K ): string {
return t[k].toString()
}
like image 91
Nadia Chibrikova Avatar answered Jun 05 '26 00:06

Nadia Chibrikova



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!