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

React, Typescript, how to check key values

I have this type:

interface MyType {
   name: string
   age: number
   friend: Person
}

and consider this state:

const [myState, setMyState] = useState<MyType>({.....})

and I have this function that changes a filed inside useState:

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

const handleChange = (filed: keyof MyType, value: unknown) => {
   setMyState({
      ...myState,
      [field]: value
   })
}

how can I use generics or some other work around to type the value argument in the above function?
I expect my handleChange function to throw error when wrong value is passed to a field:

handleChange("name", 5);

>Solution :

You need add generic for field argument:

import React, { useState } from 'react'

type Person = {
  tag: 'Person'
}
interface MyType {
  name: string
  age: number
  friend: Person
}

declare const DEFAULT_STATE: MyType

const App = () => {
  const [myState, setMyState] = useState<MyType>(DEFAULT_STATE)

  const handleChange = <Field extends keyof MyType>(field: Field, value: MyType[Field]) => {
    setMyState({
      ...myState,
      [field]: value
    })
  }

  handleChange('name', 'John') // ok
  handleChange('age', 'five') // expected error

}

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