索引签名参数类型不能是文字类型或泛型类型。考虑使用映射对象类型代替

Fra*_*sco 15 typescript

我正在尝试执行以下操作:

interface Collection {
   foo: string,
   bar: string
}

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

目标是拥有key: "foo" | "bar"但我收到以下错误:

索引签名参数类型不能是文字类型或泛型类型。考虑使用映射对象类型代替

但我不确定映射对象在这里如何应用。有什么帮助吗?谢谢!


编辑:

由于存在类似的问题,该问题已结束。我尝试了那里提供的解决方案,但没有设法使其与Mapped 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
}
Run Code Online (Sandbox Code Playgroud)

这还解决了将正确的值类型与正确的键关联的问题(我之前没有解决这个问题)。我不确定我是否以错误的方式使用映射和索引类型(以及是否有办法用它们来实现它),但Partial绝对看起来是我从一开始就应该采取的正确方法。

Hin*_*ich 13

使用映射类型(注意in关键字)

interface Collection {
   foo: string,
   bar: string
}

const patchCollection = (
    collection: Collection, 
    propertyToUpdate: {[key in keyof Collection]: any}
) => {
    // do something here
}
Run Code Online (Sandbox Code Playgroud)

映射类型是一种泛型类型,它使用 PropertyKeys 的联合(通常通过 keyof 创建)来迭代键以创建类型。

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

  • 另外,您可以使用“Record&lt;keyof Collection, any&gt;”代替“{[key in keyof Collection]: any}” (2认同)