TypeScript: How to deal with generic types and the keyof operator

Viewed 19306

I try to write a generic function which assembles update data for database updates.

Passed arguments:

  • record to be updated
  • property key
  • a new array item

Even though I restrict the key's type using keyof R, I cannot assign a new object with that key to a Partial<R> constant. I get the error Type '{ [x: string]: any[]; }' is not assignable to type 'Partial<R>'. What can I do to make the following code work? If I replace the generic type R by a non-generic type, it works. But this is not what I need.

Snippet on TypeScript Playground

interface BaseRecord {
    readonly a: ReadonlyArray<string>
}

function getUpdateData<R extends BaseRecord>(record: R, key: keyof R, newItem: string) {
    const updateData: Partial<R> = { [key]: [...record[key], newItem] }
    return updateData
}

interface DerivedRecord extends BaseRecord {
    readonly b: ReadonlyArray<string>
    readonly c: ReadonlyArray<string>
}
const record: DerivedRecord = { a: [], b: [], c: ["first item in c"] }
console.log(getUpdateData<DerivedRecord>(record, "c", "second item in c"))
2 Answers
Related