Home > other >  Access inner indexed type in TypeScript
Access inner indexed type in TypeScript

Time:11-02

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?

CodePudding user response:

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

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