Reputation: 6158
I want to have an array full of other array that contain string or numbers:
var mainarray: [] = [];
xy.forEach(function (foo) {
var subarray: [] = ['test', 'test', 3];
mainarray.push(subarray);
});
However I get this errors:
Type '[string, string, number]' is not assignable to type '[]'.
Argument of type '[]' is not assignable to parameter of type 'never'.
How do I have to declare the variable mainarray and subarray so that this works?
(Later I use this array to create a jsonstring)
Upvotes: 0
Views: 85
Reputation: 601
I got another error message, while trying to run this code snippet:
Type '[string, string, number]' is not assignable to type '[]'. Types of property 'length' are incompatible. Type '3' is not assignable to type '0'.
So your type declaration should be string[] |number[]
or (string | number)[]
and not just []
.
Consequently your code snippet should look like this:
var mainarray: [] = [];
xy.forEach(function (foo) {
var subarray: string[] | number[] = ['test', 'test', 3];
orders.push(subarray);
});
Upvotes: 0
Reputation: 1298
not quite sure what you're trying to accomplish here, so I can't provide a better answer without context, but you can do it like this:
let mainarray = [];
let xy = [1,2];
function test() {
xy.forEach(x => {
mainarray = [ ...mainarray, ['test', 'test', 3]];
})
console.log(mainarray);
}
Upvotes: 0
Reputation: 12960
Give the type of your array as:
var mainarray: Array<number | string>[] = [];
Upvotes: 3