Typescript 和 React 使用空类型数组设置初始状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51305171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript and React setting initial state with empty typed array
提问by Vlives
Say I have the following snippet:
假设我有以下代码段:
interface State {
alarms: Alarm[];
}
export default class Alarms extends React.Component<{}, State> {
state = {
alarms: []
};
Since I am trying to set alarms: []
Typescript doesn't like it, as [] != Alarm[]
. I found that I can use alarms: new Array<Alarm>()
which initializes an empty typed array, however I don't really like this syntax - is there an easier/better approach?
由于我试图设置alarms: []
Typescript 不喜欢它,因为[] != Alarm[]
. 我发现我可以使用alarms: new Array<Alarm>()
which 初始化一个空类型的数组,但是我真的不喜欢这种语法 - 有更简单/更好的方法吗?
回答by Titian Cernicova-Dragomir
The problem is that when you create a field in a class the compiler will type that field accordingly (either using the explicit type or an inferred type from the initialization expression such as in your case).
问题是,当您在类中创建字段时,编译器将相应地键入该字段(使用显式类型或从初始化表达式中推断出的类型,例如在您的情况下)。
If you want to redeclare the field, you should specify the type explicitly :
如果要重新声明该字段,则应明确指定类型:
export default class Alarms extends React.Component<{}, State> {
state: Readonly<State> = {
alarms: []
};
}
Or set the state in the constructor:
或者在构造函数中设置状态:
export default class Alarms extends React.Component<{}, State> {
constructor(p: {}) {
super(p);
this.state = {
alarms: []
};
}
}
You could also cast the array to the expected type, but if there are a lot of fields it would be better to let the compiler check the object literal for you.
您也可以将数组转换为预期的类型,但如果有很多字段,最好让编译器为您检查对象文字。
回答by Air1
Would
将
alarms: [] as Alarm[]
alarms: [] as Alarm[]
work for Typescript and for you ?
为 Typescript 和你工作?
See this question on how you can cast arrays in Typescript : TypeScript casting arrays
请参阅有关如何在 Typescript 中转换数组的问题:TypeScript cast arrays
回答by rahulnikhare
Declaration:
宣言:
alarms: Array<Alarm>
alarms: Array<Alarm>
Initialization in state :
状态初始化:
this.setState({
var1:'',
var2:''
});
I prefer the above declaration
我更喜欢上面的声明