Reputation: 35
I'm having trouble returning a typesafe typescript v3.5 array without declaring it in the method body. This array should contain multiple string arrays.
I'd like to do something like this:
foo(): Array<Array<string>>:
// do something
return new Array<Array: string>>
Bonus: How to return an array, which contains arrays without declaring all of those arrays in the body of the code?
UPDATE:
foo(): Array<Array<string>> {
// calculation of 'someSize' and 'anotherSize'
// init of both arrays:
let tempPartOfSpeechArr: string[] = new Array(someSize);
let tempLinguisticUsageArr: string[] = new Array(anotherSize);
let arrContainer = new Array(2);
arrContainer[0] = tempPartOfSpeechArr;
arrContainer[1] = tempLinguisticUsageArr;
return arrContainer;
actually I just want to return the arrContainer containing both arrays. I try to minimize codelines but dont want to loose readability
Upvotes: 1
Views: 6886
Reputation: 1075755
You can just return the result of an array literal:
foo(): Array<Array<string>> {
// calculation of 'someSize' and 'anotherSize'
// init of both arrays:
let tempPartOfSpeechArr: string[] = new Array(someSize);
let tempLinguisticUsageArr: string[] = new Array(anotherSize);
return [tempPartOfSpeechArr, tempLinguisticUsageArr]; // <===================
}
That shouldn't be unclear to anyone who can handle TypeScript in the first place. :-)
Side note: There's almost never any reason to use new Array
or to predefine the length of your arrays. These lines:
let tempPartOfSpeechArr: string[] = new Array(someSize);
let tempLinguisticUsageArr: string[] = new Array(anotherSize);
can more simply and idiomatically be:
let tempPartOfSpeechArr: string[] = [];
let tempLinguisticUsageArr: string[] = [];
The only difference is that your original code created sparse arrays (their length
s were > 0 but they had no entries in them), whereas the revised code doesn't. In general, avoid sparse arrays as they can defeat JavaScript engine optimizations designed to use true arrays under the covers.
Side note 2: You're mixing two different styles of type decarations for your arrays. foo
's return type is declared as Array<Array<string>>
, but you're declaring your arrays using the array-specific syntax string[]
. It's fine to do that, but you might consider using array syntax throughout by declaring foo
as string[][]
:
foo(): string[][] {
// ....
Full example (on the playground), returning an array with two arrays, the first containing the unique non-digits in the string, the second containing the unique digits in the string:
function ex(str: string): string[][] {
const a: string[] = [...new Set(str.replace(/\d/g, ""))];
const b: string[] = [...new Set(str.replace(/\D/g, ""))];
return [a, b];
}
console.log(ex("Testing 1 2 3 testing"));
// =>
// [
// ["T", "e", "s", "t", "i", "n", "g"],
// ["1", "2", "3"]
// ]
Upvotes: 2