0
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?

1 Answer 1

1

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
}

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.