[英]Generic type indexing. TS2536: Type 'string' cannot be used to index type 'T'
I will appreciate it a lot if you could suggest what would be a correct way to type the method below:如果您能建议键入以下方法的正确方法,我将不胜感激:
interface TestT {
[index: string]: any
}
function _defaultUpdateStateMutation<T extends TestT> (
state: T,
options: {
value: Object,
valueName: string
}
) {
const { value, valueName } = options
// TS2536: Type 'string' cannot be used to index type 'T'.
if (valueName) {
state[valueName] = value
} else if (value) {
Object.keys(value).forEach(valueName => {
state[valueName] = value[valueName]
})
}
}
TypeScript Playground .打字稿游乐场。
You must tell the ts
compiler that valueName
is key of T:您必须告诉
ts
编译器valueName
是 T 的键:
And also convert Object.keys(value)
as a Array<keyof T>
并将
Object.keys(value)
转换为Array<keyof T>
function _defaultUpdateStateMutation<T extends TestT> (
state: T,
options: {
value: any,
valueName: keyof T
}
) {
const { value, valueName } = options
if (valueName) {
state[valueName] = value
} else if (value) {
(Object.keys(value) as Array<keyof T>).forEach(valueName => {
state[valueName] = value[valueName]
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.