简体   繁体   中英

extend typescript type in react setState

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?

  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[]>([])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM