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