typescript 类型 [] 中缺少 JavaScript 类型脚本属性 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52362468/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:39:16  来源:igfitidea点击:

JavaScript type script Property 0 is missing in type []

javascripttypescript

提问by stevenpcurtis

I want to have an array of an object as follows.

我想要一个对象数组,如下所示。

However typescript throws up an error Property 0 is missing in type []

然而,打字稿抛出了一个错误属性 0 在类型 [] 中丢失

let organisations: [{name: string, collapsed: boolean}] = [];

回答by Titian Cernicova-Dragomir

What you are defining is a tuple type(an array with a fixed number of elements and heterogeneous types). Since tuples have a fixed number of elements the compiler checks the number of elements on assignment.

您定义的是元组类型(具有固定数量元素和异构类型的数组)。由于元组具有固定数量的元素,编译器会在赋值时检查元素的数量。

To define an array the []must come after the element type

要定义数组,[]必须在元素类型之后

let organisations: {name: string, collapsed: boolean}[] = [];

Or equivalently we can use Array<T>

或者等效地我们可以使用 Array<T>

let organisations: Array<{name: string, collapsed: boolean}> = [];

回答by Praveen Poonia

You can define tuples types like -

您可以定义元组类型,如 -

type organisationsType = {name: string, collapsed: boolean};
let organisations: organisationsType[];

Remember array the []must come after the element type, like organisationsTypein above example.

记住数组[]必须在元素类型之后,就像organisationsType上面的例子一样。