Advanced TypeScript Exercises - Question 8

macsikora

Pragmatic Maciej

Posted on April 6, 2020

Advanced TypeScript Exercises - Question 8

Welcome back! Let's go back on track after bonus questions. This question will be less abstract, and more practical, we will land more at value level 🚁.

We have a function concatToField which takes object, and key of this object, and string value. The purpose of this function is to create a new object with concatenated property object[key] with third argument.

The question - How to type generic types T and K in the definition of concatToField function in order to achieve compile time guarantee that obj[key] can be only string.

const concatToField =
  <T /* here your code 💪*/, K /* here your code 💪*/>(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
}
// tests
const test = { fieldStr: 'text', fieldNum: 1, fieldStr2: 'text' };
concatToField(test, 'fieldStr', 'test'); // should be ok 👌
concatToField(test, 'fieldNum', 'test'); // should be error fieldNum is not string field 🛑
concatToField(test, 'notExistingField', 'test'); // should be error - no such field 🛑
concatToField(test, 'fieldStr2', 'test'); // should be ok 👌
Enter fullscreen mode Exit fullscreen mode

Full code available in the playground

Important - body of the function should remain unchanged, no type assertion (as), or any changes of the body are allowed. The only thing needs to be done is constraint on T and K generic types.

Post your answers in comments (preferred links to the playground). Have fun! Answer will be published soon!

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 6, 2020

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

Sign up to receive the latest update from our blog.

Related

Type | Treat The Finale
typescript Type | Treat The Finale

October 31, 2020