【发布时间】:2018-03-02 00:34:41
【问题描述】:
我的一个 React 组件中有以下方法:
getRandomColor(){
const { colors }: { colors: any } = this.state;
return colors[Math.floor(Math.random() * colors.length)];
}
但是,打字稿在解构语句中给我一个错误,我不知道为什么:
类型 'Readonly' 不能分配给类型 '{ colors: any; }'。 “只读”类型中缺少属性“颜色”。
谁能告诉我为什么?我肯定在构造函数中设置了this.state.colors,即使我没有,我也不完全确定它为什么会抛出这个错误。
【问题讨论】:
-
所以你是trying to do this?似乎有效,也许您的状态设置不正确。
-
我想我可能需要为构造函数中的
this.state =语句分配一个类型接口。出于某种原因,我认为类型会被自动推断 -
它告诉你 Readonly 是一种我觉得很奇怪的类型。不认为 readonly 是一种类型。那或者我误解了错误信息。
-
似乎在
this.state中找不到颜色变量的类型-当我将行更改为const colors = this.state.colors时,错误变为:Property 'colors' does not exist on type 'Readonly<{}>'。但现在的问题是如何定义该类型? -
为什么它是只读的?呵呵。好吧,它应该是只读的,并使用 setState 进行修改,所以我想这有点道理。
标签: javascript reactjs typescript ecmascript-6