DEV Community

Discussion on: Advanced TypeScript Exercises - Question 8

Collapse
 
macsikora profile image
Pragmatic Maciej • Edited

Hi David thank you for the answer.
But your code doesn't make errors when it should, so there are no compile time guarantees. I put in the snippet two places where the error should occur, you see there 🛑 icon. Even more the code you have provided compiles for any second argument like concatToField(test, 'anything', 'test');.

So try again! And good luck.

Collapse
 
dwjohnston profile image
David Johnston • Edited

Ah, was just missing some brackets. :/

const concatToField =
  <T extends Record<string, any>,
    K extends keyof T & (T[K] extends string ? string : never)>(obj: T, key: K, payload: string): T => {
    const prop = obj[key]; // compile error should not be here
    return { ...obj, [key]: prop.concat(payload) }; // compile error should not be here
}

Playground