A
A
ArturMavlidov2022-04-02 18:05:26
typescript
ArturMavlidov, 2022-04-02 18:05:26

What's wrong with typescript typing?

type Category = {
  id: number,
  name: string,
  products: number[]
}

type Items = {
  [key: string]: any[]
}

export interface IGoods {
  categories: Category[];
  items: Items;
}

const App: React.FC = () => {
  const [goods, setGoods] = useState<IGoods | object>({});

  useEffect(() => {
    fetch("https://delivery-f1999-default-rtdb.firebaseio.com/goods.json")
      .then((data) => data.json())
      .then((data) => setGoods(data))
  }, [])

  return (
    <>
      <Categories categories={goods.categories}/>
    </>
  );
};


I'm trying to pass categories to the Categories component, but the error is Property 'categories' does not exist on type 'object | IGoods'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2022-04-02
@ArturMavlidov

Rather, it is better to use useState<T | null>(null), because in such a case, you can easily check the value in the conditional renderer. And if you declare something like in your component React.FC<{ data: T }>, then Object(more precisely, nothing, except in Tan honest way) cannot be thrown inside.
https://codesandbox.io/s/qna-q-1135320-6iz66s

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question