简体   繁体   中英

Multiple types of nested properties in TypeScript

I would like to apply types for a variable something . something can be:

  • a string
  • an array of string
  • a key-value pair: the key is always a string, and the value can be another something : either a key-value pair (possibly multiple level nested), a string, or an array of string

Suppose I have a JSON response which matches the structure of the type of something :

{
  something: {
    fox: 'jump',
    rabbit: {
      bunny: 'carrot',
      alaska: 'hay'
    },
  }
}

What I'm doing in TypeScript is:

type SomethingType = {
  [key: string]: string | string[] | SomethingType
};

interface SomethingProps {
  something: SomethingType | null
}

class MyApp extends React.Component<SomethingProps> {
  render() {
    const itWorks = this.props.something.fox;
    const itDoesNotWork = this.props.something.rabbit.bunny;
    return ...
  }

  ...
}

When my IDE (VS Code) checks the types, for itWorks it works. For itDoesNotWork , it indicates that its type is any and gives the error message below:

Property 'bunny' does not exist on type 'string | string[] | SomethingType'.
Property 'bunny' does not exist on type 'string'.
ts(2339)

What should I do if want the value of something.rabbit.bunny , or even more level nested properties, all have the type of either string | string[] | SomethingType string | string[] | SomethingType string | string[] | SomethingType ?

Maybe adding this keyword in front of something to refer:

class MyApp extends React.Component<SomethingProps> {
  itWorks = this.something.fox;
  itDoesNotWork = this.something.rabbit.bunny;
  ...
}

Or this.props :

class MyApp extends React.Component<SomethingProps> {
  itWorks = this.props.something.fox;
  itDoesNotWork = this.props.something.rabbit.bunny;
  ...
}

You should also delete the const keyword in front of your properties because you are in a class.

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