简体   繁体   English

通用类型索引。 TS2536:类型“字符串”不能用于索引类型“T”

[英]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]
        })
    }
}

PlayGroundLink 游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型 &#39;string[]&#39; 不能用作索引 type.ts(2538) - Type 'string[]' cannot be used as an index type.ts(2538) 类型“未定义”不能用作使用泛型类型的索引类型 - Type 'undefined' cannot be used as an index type using Generic type 表达式类型“字符串”不能用作索引类型 - Expression Type 'String' cannot be used as an index type 类型 &#39;undefined&#39; 不能用作索引 type.ts(2538) - Type 'undefined' cannot be used as an index type.ts(2538) Typescript:类型“未定义”不能用作索引类型.ts(2538) - Typescript: Type 'undefined' cannot be used as an index type.ts(2538) Typescript 泛型类型 - 类型“keyof T1”不能用于索引类型 - Typescript generic type - Type 'keyof T1' cannot be used to index type 类型错误:类型 &#39;string[]&#39; 不能用作索引类型 - Type error: Type 'string[]' cannot be used as an index type TypeScript - ts(7053):元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引 - TypeScript - ts(7053) : Element implicitly has an 'any' type because expression of type 'string' can't be used to index 类型“ {}”不能用作索引类型 - Type '{}' cannot be used as an index type TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ A:数字; B:数字 - TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ A: number; B: number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM