Generic type indexing. TS2536: Type ‘string’ cannot be used to index type ‘T’

  javascript, typescript

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.

Source: Ask Javascript Questions

LEAVE A COMMENT