[英]Multiple types of nested properties in TypeScript
I would like to apply types for a variable something
.我想为变量
something
应用类型。 something
can be: something
可以是:
something
: either a key-value pair (possibly multiple level nested), a string, or an array of stringsomething
:键值对(可能是多级嵌套)、字符串或字符串数组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.