Destructuring an object in TS

Viewed 837

I have this TS code, and I want to make that part to be also typed :

    const { data: { person, car, another } }: any = useContext(MyContext);

the issue here is that ES lint says: warning Unexpected any. Specify a different type @typescript-eslint/no-explicit-any

I have 3 interfaces created for person, car, another and I want to reuse them after the useContext. My objective is to just share person, car, another

Any clues?

1 Answers

Type annotations cannot be placed in destructuring operations, the : character already has a use there as a way to assign a property being destructed to a new name.

const { person: p2 } = { person: "Name" }
p2 === "Name" // true

You could replace the any with the type you expect from useContext.

const { data: { person, car, another } }: { data: { person: Person, car: Car, another: Another } }
  = useContext(MyContext);

But ideally the type of the return of useContext should be inferred from the parameter passed to it, when you create the context you should have a line like:

type ContextType = {data: {person: Person, car: Car, another: Another}}
const MyContext = createContext<ContextType>({/* default value */})

When you then use useContext the value that is returned will already have the ContextType and your destructuring will be typed without required any type annotations.

Related