Advanced TypeScript Exercises - Answer 8

macsikora

Pragmatic Maciej

Posted on April 22, 2020

Advanced TypeScript Exercises - Answer 8

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.

đź’– đź’Ş đź™… đźš©
macsikora
Pragmatic Maciej

Posted on April 22, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related