【发布时间】:2021-09-01 01:12:01
【问题描述】:
我有一个由多个公共成员组成的课程。
为简单起见,我们假设:
class ComponentData {
id: number;
type: ComponentType;
location: ComponentLocation;
label: string;
value: number;
}
我确实定义了一个类型:
type Layout = {[field in keyof ComponentData]?: InputSchema};
使用 Object.keys(layout) 我正在为不同的 ComponentTypes 显示不同的输入集。这很好用,但是稍后输入 onChange 我正在尝试修改源 ComponentData。
function onPropertyChange(newValue: unknown, fieldName: string) {
selectedItem[fieldName] = newValue;
}
我收到了:
TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“组件数据”。在“ComponentData”类型上找不到带有“string”类型参数的索引签名。
我尝试遵循此处建议的解决方案: https://stackoverflow.com/a/66838662/8191341 如下:
function onPropertyChange(newValue: unknown, fieldName: string) {
const key = fieldName as keyof ComponentData;
selectedItem![key] = newValue;
}
但后来收到了:
TS2322:类型“InputValues”不可分配给类型“从不”。类型“未定义”不可分配给类型“从不”。
有什么想法吗? :)
PS。使用 //@ts-ignore 它按预期工作,但我对解决方案不满意。
【问题讨论】:
标签: javascript string typescript types