DEV Community

Hasan TEZCAN
Hasan TEZCAN

Posted on

4 3

Generic typing a hash-map with dynamic key and T array

I have a JSON like this. I need an add a type of this JSON. As you can see this is a hash-map structure let's see how we declare the hash-map interface in typescript.

hash-map json example

I declared this hash-map in my useState like that.

  const [faqCategories, setFaqCategories] = useState<FAQ[]>([]);
Enter fullscreen mode Exit fullscreen mode

We are declaring hash-map like that in typescript.

export interface FAQ {
  [key: string]: Category[];
} 
Enter fullscreen mode Exit fullscreen mode

The whole type system like this for this JSON.

export interface Question {
  question: string;
  answer: string;
}
export interface Category {
  categoryName: string;
  iconName: string;
  questions: Question[];
}

export interface FAQ {
  [key: string]: Category[];
}
Enter fullscreen mode Exit fullscreen mode

Source: https://stackoverflow.com/a/52913569/10694425

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!