簡體   English   中英

TypeScript 中的多種嵌套屬性

[英]Multiple types of nested properties in TypeScript

我想為變量something應用類型。 something可以是:

  • 一個字符串
  • 一個字符串數組
  • 鍵值對:鍵始終是字符串,值可以是其他something :鍵值對(可能是多級嵌套)、字符串或字符串數​​組

假設我有一個 JSON 響應,它匹配something類型的結構:

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

我在 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 ...
  }

  ...
}

當我的IDE(VS代碼)檢查類型, itWorks它的工作原理。 對於itDoesNotWork ,它表明它的類型是any並給出以下錯誤消息:

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

如果想要something.rabbit.bunny的值,甚至更多級別的嵌套屬性,我應該怎么做,所有的類型都是string | string[] | SomethingType string | string[] | SomethingType string | string[] | SomethingType

也許在要引用的something前面添加this關鍵字:

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

或者this.props

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

您還應該刪除屬性前面的const關鍵字,因為您在一個類中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM