Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access inner indexed type in TypeScript

I have a type that’s generated by GraphQL codegen that looks like the following:

export type GetAudioQuery = { audioByPk?: { address: string, id: any, title?: string | null, subtitle?: string | null, audio_tags: Array<{ tagId: any }> } | null };

In my React component, I want to type my state, but I am not entirely sure how to access the inner audio_tags from above. My first attempt was something like the following:

const [currTags, setCurrTags] = useState<GetAudioQuery['audioByPk']['audio_tags']>([]);

What’s the correct way to type my useState here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since audioByPk is optional, you would have to use NonNullable first:

const [currTags, setCurrTags] = useState<NonNullable<GetAudioQuery['audioByPk']>['audio_tags']>([]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading