Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead

Tags:

typescript

I'm trying to do the following:

interface Collection {
   foo: string,
   bar: string
}

const patchCollection = (
    collection: Collection, 
    propertyToUpdate: {[key: keyof Collection]: any}
) => {
    // do something here
}

The goal would be to have key: "foo" | "bar" but I get the following error:

An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead

But I'm not sure how a mapped object would apply here. Any help? Thanks!


EDIT:

The question got close due to similar questions existing. I tried the solutions provided there but I didn't manage to make it work with the Mapped type. However, I was able to solve my issue with The Partial Utility Type (https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype )

interface Collection {
   foo: string,
   bar: string
}

const patchCollection = (
    collection: Collection, 
    propertyToUpdate: Partial<Collection>
) => {
    // do something here
}

This solves also the issue of having the right value type associated with the right key (which I didn't address previously). I'm not sure if I was using the Mapped and Index types in the wrong way (and if there is a way to achieve it with those), but Partial definitely seems like the right approach I should have taken from the beginning.

like image 930
Francesco Avatar asked Sep 12 '25 22:09

Francesco


1 Answers

Use a mapped type (notice the in keyword)

interface Collection {
   foo: string,
   bar: string
}

const patchCollection = (
    collection: Collection, 
    propertyToUpdate: { [key in keyof Collection]: Collection[key] } // <--
) => {
    // do something here
}

A mapped type is a generic type which uses a union of PropertyKeys (frequently created via a keyof) to iterate through keys to create a type.

docs: https://www.typescriptlang.org/docs/handbook/2/mapped-types.html

edit:

As the OP mentioned, this seems like a good usecase for the Partial utility type as well.

const patchCollection = (
    collection: Collection, 
    propertyToUpdate: Partial<Collection> // <--
) => {
    // do something here
}
like image 94
Hinrich Avatar answered Sep 15 '25 13:09

Hinrich