0

How do I map an string array string[] to a 2 dimensional array with strings [string, string]?

I tried

const animals: string[] = ['Dog', 'Cat', 'Mouse'];
// This throws an error
let splittedArray: [string, string] = animals.slice(0,2);

// This doesn't throw an error
// let splittedArray: [string, string] = ['Dog', 'Cat'];

// Error Message
// Type 'string[]' is missing the following properties from type '[string, string]': 0, 1 ts(2739) 

My desired output should be:

console.log(splittedArray);
// ['Dog', 'Cat']
5
  • 1
    What you tried is not an 2D array of strings; it is a array with 2 elements of type string Commented Dec 6, 2019 at 12:25
  • I know, it is just an example. I really need an array with exactly 2 elements of type string. Commented Dec 6, 2019 at 12:26
  • What does your desired output look like? Commented Dec 6, 2019 at 12:26
  • 1
    you need animals.slice(0, 2)... 0, 1 would give you just ['Dog'] Commented Dec 6, 2019 at 12:28
  • Still: Type 'string[]' is missing the following properties from type '[string, string]': 0, 1 Commented Dec 6, 2019 at 12:29

2 Answers 2

1

just change type declaration to this... The as operator's mostly designed for *.tsx files to avoid the syntax ambiguity. Working StackBlitz Link is

const animals: string[] = ['Dog', 'Cat', 'Mouse'];
let splittedArray = animals.slice(0,2) as [string,string];
console.log(splittedArray)
Sign up to request clarification or add additional context in comments.

1 Comment

It works, perfect. Thank you! Still don't know what this cryptic error message means, but anyways. At least a solution for now
1

Do you want a 2D array or an array with 2 elements? This seems to work for your output:

    const animals: string[] = ['Dog', 'Cat', 'Mouse'];
    let splittedArray: string[] = animals.slice(0,2);

4 Comments

I want an array with exactly 2 elements. [string, string]
Then my answer till work it will give you the output of : ['Dog', 'Cat']
That's what my question is about. I know how to extract 2 elements from an array. My question is to set the value of an array to an array with [string, string]
Why the downvote? the reason for your error message is because animals.slice(0,2) is of type String[]. You can not write [string, string]. If you splice at index 0 with 2 element you get an array with 2 elements, starting from index 0. Is that not what you want?

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.