DEV Community

Discussion on: Advanced TypeScript Exercises - Question 8

Collapse
 
wangfengming profile image
wangfengming
type StringKeys<T extends object> = {
  [K in keyof T]: T[K] extends string ? K : never;
}[keyof T];

const concatToField =
  <T extends Record<string, any>, K extends StringKeys<T>>(obj: T, key: K, payload: string): T => {
    const prop = obj[key] as unknown as string; // compile error should not be here
    return { ...obj, [key]: prop.concat(payload) }; // compile error should not be here
  }
Enter fullscreen mode Exit fullscreen mode