[英]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.