最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - JavaScript type script Property 0 is missing in type [] - Stack Overflow

programmeradmin1浏览0评论

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

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

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

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

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

let organisations: [{name: string, collapsed: boolean}] = [];
Share Improve this question asked Sep 17, 2018 at 7:08 stevenpcurtisstevenpcurtis 2,0013 gold badges23 silver badges49 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 44

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>

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

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 organisationsType in above example.

发布评论

评论列表(0)

  1. 暂无评论