简体   繁体   English

TypeScript 中的多种嵌套属性

[英]Multiple types of nested properties in TypeScript

I would like to apply types for a variable something .我想为变量something应用类型。 something can be: something可以是:

  • 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键值对:键始终是字符串,值可以是其他something :键值对(可能是多级嵌套)、字符串或字符串数​​组

Suppose I have a JSON response which matches the structure of the type of something :假设我有一个 JSON 响应,它匹配something类型的结构:

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

What I'm doing in TypeScript is:我在 TypeScript 中所做的是:

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.当我的IDE(VS代码)检查类型, itWorks它的工作原理。 For itDoesNotWork , it indicates that its type is any and gives the error message below:对于itDoesNotWork ,它表明它的类型是any并给出以下错误消息:

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如果想要something.rabbit.bunny的值,甚至更多级别的嵌套属性,我应该怎么做,所有的类型都是string | string[] | SomethingType string | string[] | SomethingType string | string[] | SomethingType ? string | string[] | SomethingType

Maybe adding this keyword in front of something to refer:也许在要引用的something前面添加this关键字:

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

Or this.props :或者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.您还应该删除属性前面的const关键字,因为您在一个类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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