简体   繁体   中英

How to access nested data interface in React TypeScript

In React TypeScript, what is the appropriate way to access data in a nested interface like the one below?

export interface School {
  prices: Array<{
    state: {
      response_header?: {
        school_type_opportunities?: Array<{ benefit_type_opportunity?: string }>;
        school_alternative_products?: Array<{
          school_alternative_cost_share_incentive?: string;
          school_alternative_description?: string;
          school_alternative_id?: string;
          school_attendance_required?: Array<{
            school_attendance_location?: string;
            school_attendance_blabla?: string;
            school_attendance_blabla2?: string;
          }>;
        }>;

I want to get access to:

  • school_type_opportunities
  • school_alternative_description
  • school_attendance_location

TypeScript is merely type-safe JavaScript, ie you'd practise the same methodologies and find eg

const schoolTypeOportunities =
  School.prices[x].state.response_header.school_type_opportunities;

As prices is of type Array here (and depending on your application) you'd need to know which index is relevant and change x . Alternatively, if multiple, you can might find map , filter , or reduce convenient to extract your wanted items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM