【发布时间】:2021-06-04 22:07:34
【问题描述】:
以前在 Typescript 3.3 中,可以使用“keyof interface”关键字将变量定义为允许动态访问具有所述接口类型的实例的属性的类型。
我想使用它来编写一个函数,该函数将字段和值作为参数并将值分配给对象的字段。然后可以从我的 React 应用程序中的多个输入字段调用此函数,如下所示:
interface Product {
id: number
name: string
price_amount: number
price_currency: string
}
const myProduct = {
id: 0,
name: "My Product",
price_amount: 100,
price_currency: "€",
}
function handleObjectFieldUpdate(field: keyof Product, value: string) {
{...} // Convert value to the respective type
myProduct[field] = value
}
然而,在 Typescript 4.3 中,此代码不再编译并出现错误
Type 'string' is not assignable to type 'never'.ts(2322).
链接到不编译Typescript 4.3 Example
handleObjectFieldUpdate 函数的更新实现是什么样的?
【问题讨论】:
标签: typescript