Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define an "any" array in an object literal in Typescript? [duplicate]

The following fails with an error.

TS7018: Object literal's property 'scopes' implicitly has an 'any[]' type.

I want to define foo as an array of any. How do I do this in an object literal?

{
  foo: [],
}
like image 341
Ben Aston Avatar asked Jul 25 '16 14:07

Ben Aston


People also ask

How do you define an array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

How do you create an array of object literals in a loop?

I need to create an array of object literals like this: var myColumnDefs = [ {key:"label", sortable:true, resizeable:true}, {key:"notes", sortable:true,resizeable:true},...... The value of key should be results[i]. label in each element of the array.

How do you define an object in TS?

In TypeScript, object is the type of all non-primitive values (primitive values are undefined , null , booleans, numbers, bigints, strings). With this type, we can't access any properties of a value.

Is object a data type in TypeScript?

object is a type that represents the non-primitive type, i.e. anything that is not number , string , boolean , bigint , symbol , null , or undefined . Argument of type 'undefined' is not assignable to parameter of type 'object | null'.Argument of type 'undefined' is not assignable to parameter of type 'object | null'.


2 Answers

If it's a array then:

let foo: any[] = [];

But there's no object literal here.
If you want foo to be an object with an array then:

let foo: { array: any[] } = { array: [] }
foo.array.push(12);
foo.array.push("stirng");
like image 188
Nitzan Tomer Avatar answered Oct 05 '22 02:10

Nitzan Tomer


{
    foo: any[],
}

Array literal:

let list: any[] = [1, true, "free"];

From here:

https://www.typescriptlang.org/docs/handbook/basic-types.html

like image 43
2b77bee6-5445-4c77-b1eb-4df3e5 Avatar answered Oct 05 '22 01:10

2b77bee6-5445-4c77-b1eb-4df3e5