Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading