DEV Community

loading...
Cover image for Advanced TypeScript Exercises - Answer 8

Advanced TypeScript Exercises - Answer 8

macsikora profile image Maciej Sikora ・1 min read

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 👍
}
Enter fullscreen mode Exit fullscreen mode

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.

Discussion

pic
Editor guide