0

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)

2
  • With orders.push(subarray); you mean mainarray.push(subarray); ?? Commented Jan 5, 2019 at 15:59
  • @zyz thanks yes of course I do mean that! I corrected it Commented Jan 5, 2019 at 16:01

3 Answers 3

3

Give the type of your array as:

var mainarray: Array<number | string>[] = [];
Sign up to request clarification or add additional context in comments.

3 Comments

Only the subarray has number or string in it, the mainarray has subarrays in it. So would it be something like this: var mainarray: Array<Array<number | string>[]>[] = []; This looks kinda confusing
Notice that for each type T the following are equivalent types: Array<T> and T[]. Alternative notations for the solution @xyz has given: Array<(number | string)[]>, Array<Array<number | string>> or (number | string)[][]
@nbar: No, I think a single Array<number | string> should do. It says that the content of mainarray is of type array which in itself can contain numbers or strings. Is it not working?
0

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);
}

Comments

0

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.