0

I'm trying to make typescript happy by giving the correct type. But I can't figure out the exact syntax.

export type CategoriesType = {
  id: string;
  title: string;
  url: string;
  courses: CoursesType[];
};

const [singleCategory, setSingleCategory] = useState<CategoriesType>([] as any);

useEffect(() => {
  const categories = Categories;

  for (const category of categories) {
    setSingleCategory(category);
  }
}, [singleCategory]);

return (
  singleCategory.courses !== [] ? ...
)

This code works. But typescript complains about usage of any. I would prefer to avoid using any.

Other tries:

I get error Property 'courses' does not exist on type 'CategoriesType | []'

  const [singleCategory, setSingleCategory] = useState<CategoriesType | []>([]);

Object is possibly 'undefined'.

const [singleCategory, setSingleCategory] = useState<CategoriesType>();
8
  • 1
    Would const [singleCategory, setSingleCategory] = useState<CategoriesType[]>([]) work for your application? Commented Dec 30, 2020 at 14:51
  • Nope, I would get error Property 'courses' does not exist on type 'CategoriesType[]'. In return statement Commented Dec 30, 2020 at 14:52
  • What purpose does the array serve? Is it just a marker that "we don't have a category"? Commented Dec 30, 2020 at 14:53
  • Yes empty array, is initial value. Until Categories are fetched. Commented Dec 30, 2020 at 14:55
  • I don't display anything until categories are fetched. Commented Dec 30, 2020 at 14:55

1 Answer 1

1

Set state like below.

const [singleCategory, setSingleCategory] = useState<CategoriesType[]>([])

Also in your return singleCategory.courses doesn't make any sense because singleCategory is array type not the object type. You should match your types for state definition and usage.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.