How change object property value typescript?

interface State {
    customerId: number,
    step: string

const data: State = {
    step: 'shipping',
    customerId: 123

const setData = (key: string, value: number) => {
    data[key] = value

setData('customerId', 555)

Im try change value of customerId but got error:
No index signature with a parameter of type ‘string’ was found on type ‘State’.

How i can set new value?

>Solution :

You need to change the definition of setData to include a generic parameter K. K represents the key of State you are trying to modify. The type of value will be State[K]. This is how we can model a relation between the key and value parameter.

const setData = <K extends keyof State>(key: K, value: State[K]) => {
    data[key] = value


Leave a Reply