Home > Mobile >  Is there way to make generic Atom in Recoil
Is there way to make generic Atom in Recoil

Time:09-14

I made a atom with Recoil but I couldn't find a way to represent generic atom in Typescript.

const atom = atom<T[]>({ // <- I get error
  key: 'atom',
  default: []
})

const value = useRecoilValue<number[]>(atom) // <- specify actual value here (not working now)

How can I make it work?

CodePudding user response:

From the definition of atom function here, atom already has a generic type parameter and this should work:

const some = atom<string[]>({
  key: 'some-key',
  default: [] // now has `string[]` type
})

And from the definition of useRecoilValue we see, that generic infers automatically and you don't need to specify it:

const value = useRecoilValue(some) // inferred type of `value` is `string[]`

You should not specify type at useRecoilValue because atom already has this information

  • Related