Home > front end >  extend typescript type in react setState
extend typescript type in react setState

Time:02-01

I have this

type fruitCode = 'apple' | 'banana'
interface fruitList {
  name: fruitCode
}

const [arr, setArr] = useState<fruitList[]>([])

https://codesandbox.io/s/react-typescript-forked-xqcqz?file=/src/App.tsx:65-143

I want to add new string fruitCode when I do setArr but it doesn't make sense to alter fruitCode because the new string isn't a type of fruit. What should I do to fruitList[] to extend it?

CodePudding user response:

  1. Extend fruitList type (eg: otherList)
type fruitCode = 'apple' | 'banana'

interface fruitList {
  name: fruitCode
}

// add this type
interface otherList extends fruitList {
  name: string
}
  1. use otherList in setState
const [arr, setArr] = useState<otherList[]>([])
  •  Tags:  
  • Related