The question was about creating indexed type assignable to string. For the full question please visit Advanced TypeScript Exercises - Question 8
The Answer
const concatToField =
<T extends Record<K, string>
, K extends keyof T >(obj: T, key: K, payload: string): T => {
const prop = obj[key];
return { ...obj, [key]: prop.concat(payload) }; // works 👍
}
The key to the problem was obj[key]
which is a type of T[K]
so the whole problem comes to - how to ensure T[K]
is always string. Trying to narrow the K
type only for string
values in T
will not work, as T
can have no string fields at all, so we can end by never
(the bottom type).
The simplest solution is restricting T
to be extending Record<K, string>
, what does it mean - we say that our T
needs to have key K
being a string
. Now if we put key which will be having different value than string
there will be compilation error.
Full solution available in the playground
This series will continue. If you want to know about new exciting questions from advanced TypeScript please follow me on dev.to and twitter.
Top comments (2)
I challanged myself and in my version you can pass object with number properties but you can only edit string type ones:
Playground Link
Wow, nice! For some reason, I didn't realize that we can use "K" in "T" before we actually "declared" "K"